from __future__ import absolute_import
from nilmdb.printf import *
import nilmdb.client

import fnmatch
from argparse import ArgumentDefaultsHelpFormatter as def_form

def setup(self, sub):
    cmd = sub.add_parser("list", help="List streams",
                         formatter_class = def_form,
                         description="""
                         List streams available in the database,
                         optionally filtering by layout or path.  Wildcards
                         are accepted.
                         """)
    cmd.set_defaults(handler = cmd_list)

    group = cmd.add_argument_group("Stream filtering")
    group.add_argument("-l", "--layout", default="*",
                       help="Match only this stream layout")
    group.add_argument("-p", "--path", default="*",
                       help="Match only this path")

    group = cmd.add_argument_group("Interval details")
    group.add_argument("-d", "--detail", action="store_true",
                       help="Show available data time intervals")
    group.add_argument("-s", "--start",
                       metavar="TIME", type=self.arg_time,
                       help="Starting timestamp (free-form)")
    group.add_argument("-e", "--end",
                       metavar="TIME", type=self.arg_time,
                       help="Ending timestamp (free-form)")

def cmd_list(self):
    """List available streams"""
    streams = self.client.stream_list()
    for (path, layout) in streams:
        if not (fnmatch.fnmatch(path, self.args.path) and
                fnmatch.fnmatch(layout, self.args.layout)):
            continue

        printf("%s %s\n", path, layout)
        if not self.args.detail:
            continue

        printed = False
        for (start, end) in self.client.stream_intervals(path, self.args.start,
                                                         self.args.end):
            printf("  [ %s -> %s ]\n",
                   self.time_string(start),
                   self.time_string(end))
            printed = True
        if not printed:
            printf("  (no intervals)\n")
