from nilmdb.utils.printf import *
import nilmdb.client
import fnmatch

from argparse import ArgumentDefaultsHelpFormatter as def_form

def setup(self, sub):
    cmd = sub.add_parser("destroy", help="Delete a stream and all data",
                         formatter_class = def_form,
                         description="""
                         Destroy the stream at the specified path.
                         The stream must be empty.  All metadata
                         related to the stream is permanently deleted.

                         Wildcards and multiple paths are supported.
                         """)
    cmd.set_defaults(handler = cmd_destroy)
    group = cmd.add_argument_group("Options")
    group.add_argument("-R", "--remove", action="store_true",
                       help="Remove all data before destroying stream")
    group.add_argument("-q", "--quiet", action="store_true",
                       help="Don't display names when destroying "
                       "multiple paths")
    group = cmd.add_argument_group("Required arguments")
    group.add_argument("path", nargs='+',
                       help="Path of the stream to delete, e.g. /foo/bar/*",
                       ).completer = self.complete.path
    return cmd

def cmd_destroy(self):
    """Destroy stream"""
    streams = [ s[0] for s in self.client.stream_list() ]
    paths = []
    for path in self.args.path:
        new = fnmatch.filter(streams, path)
        if not new:
            self.die("error: no stream matched path: %s", path)
        paths.extend(new)

    for path in paths:
        if not self.args.quiet and len(paths) > 1:
            printf("Destroying %s\n", path)

        try:
            if self.args.remove:
                count = self.client.stream_remove(path)
            self.client.stream_destroy(path)
        except nilmdb.client.ClientError as e:
            self.die("error destroying stream: %s", str(e))
