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

def setup(self, sub):
    cmd = sub.add_parser("metadata", help="Get or set stream metadata",
                         description="""
                         Get or set key=value metadata associated with
                         a stream.
                         """,
                         usage="%(prog)s path [-g [key ...] | "
                         "-s key=value [...] | -u key=value [...]]")
    cmd.set_defaults(handler = cmd_metadata)

    group = cmd.add_argument_group("Required arguments")
    group.add_argument("path",
                       help="Path of stream, e.g. /foo/bar")

    group = cmd.add_argument_group("Actions")
    exc = group.add_mutually_exclusive_group()
    exc.add_argument("-g", "--get", nargs="*", metavar="key",
                     help="Get metadata for specified keys (default all)")
    exc.add_argument("-s", "--set", nargs="+", metavar="key=value",
                     help="Replace all metadata with provided "
                     "key=value pairs")
    exc.add_argument("-u", "--update", nargs="+", metavar="key=value",
                     help="Update metadata using provided "
                     "key=value pairs")

def cmd_metadata(self):
    """Manipulate metadata"""
    if self.args.set is not None or self.args.update is not None:
        # Either set, or update
        if self.args.set is not None:
            keyvals = self.args.set
            handler = self.client.stream_set_metadata
        else:
            keyvals = self.args.update
            handler = self.client.stream_update_metadata

        # Extract key=value pairs
        data = {}
        for keyval in keyvals:
            kv = keyval.split('=')
            if len(kv) != 2 or kv[0] == "":
                self.die("Error parsing key=value argument '%s'", keyval)
            data[kv[0]] = kv[1]

        # Make the call
        try:
            handler(self.args.path, data)
        except nilmdb.client.ClientError as e:
            self.die("Error setting/updating metadata: %s", str(e))
    else:
        # Get (or unspecified)
        keys = self.args.get or None
        try:
            data = self.client.stream_get_metadata(self.args.path, keys)
        except nilmdb.client.ClientError as e:
            self.die("Error getting metadata: %s", str(e))
        for key, value in sorted(data.items()):
            # Omit nonexistant keys
            if value is None:
                value = ""
            printf("%s=%s\n", key, value)
