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

def setup(self, sub):
    cmd = sub.add_parser("remove", help="Remove data",
                         description="""
                         Remove all data from a specified time range within a
                         stream.  If multiple streams or wildcards are provided,
                         the same time range is removed from all streams.
                         """)
    cmd.set_defaults(handler = cmd_remove)

    group = cmd.add_argument_group("Data selection")
    group.add_argument("path", nargs='+',
                       help="Path of stream, e.g. /foo/bar/*",
                       ).completer = self.complete.path
    group.add_argument("-s", "--start", required=True,
                       metavar="TIME", type=self.arg_time,
                       help="Starting timestamp (free-form, inclusive)",
                       ).completer = self.complete.time
    group.add_argument("-e", "--end", required=True,
                       metavar="TIME", type=self.arg_time,
                       help="Ending timestamp (free-form, noninclusive)",
                       ).completer = self.complete.time

    group = cmd.add_argument_group("Output format")
    group.add_argument("-q", "--quiet", action="store_true",
                       help="Don't display names when removing "
                       "from multiple paths")
    group.add_argument("-c", "--count", action="store_true",
                       help="Output number of data points removed")
    return cmd

def cmd_remove(self):
    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)

    try:
        for path in paths:
            if not self.args.quiet and len(paths) > 1:
                printf("Removing from %s\n", path)
            count = self.client.stream_remove(path,
                                              self.args.start, self.args.end)
            if self.args.count:
                printf("%d\n", count);
    except nilmdb.client.ClientError as e:
        self.die("error removing data: %s", str(e))

    return 0
