#!/usr/bin/env python
#coding=utf8

'''
CloudControl right releated commands
'''

from cccli.exception import *
from sjrpc.core.exceptions import *
from cccli.printer import Printer, color
from cccli.command.command import Command, TqlCommand

class Command_rights(TqlCommand):
    '''List account rights'''

    def __init__(self, cli, argv0):
        TqlCommand.__init__(self, cli, argv0)
        self.set_usage("%prog [options] [tql]")
        self.tql_filter += "&a&r=cli"
        self.remove_option("--direct")
        self.remove_option("--quiet")
        self.remove_option("--index")

    def __call__(self, argv):
        # Parse argline
        self.parse_args(argv)
        # append current login if nothing asked
        if len(self.args) == 0:
            tql = "a=%s"%self.cli.settings["login"]
        else:
            tql = "".join(self.args)
        # ask server
        al = self.rpccall("rights", tql, _direct=True, _status=False)
        # display answer
        for (a, rl) in al.items():
            self.printer.out("%sa:%s%s%s"%(self.tdtc("a"), self.tdc("a"), a, color["reset"]))
            for i,r in enumerate(rl):
                tags = " ".join([ "%s%s:%s%s"%(self.tdtc(t), t, self.tdc(t), v) for (t,v) in r.items() ])
                self.printer.out("[%s] %s%s"%(i,tags, color["reset"]))

    def remote_functions(self):
        return set(('rights',))


class Command_addright(TqlCommand):
    '''Add or edit account right'''

    def __init__(self, cli, argv0):
        TqlCommand.__init__(self, cli, argv0)
        self.tql_filter += "&a&r=cli"
        self.set_usage('''%prog [options] <account tql> <right tql> <method> <target> [index]

<method> is the name of the rpc command to allow
<target> can be allow or deny''')

    def __call__(self, argv):
        # argv check
        self.parse_args(argv)
        if len(self.args) == 4:
            self.args.append(None)
        elif len(self.args) == 5:
            self.args[4] = int(self.args[4])
        else:
            raise cmdBadArgument()
        # rpc call
        self.rpccall("addright",
                    self.args[0],
                    self.args[1],
                    self.args[2],
                    self.args[3],
                    self.args[4])

    def remote_functions(self):
        return set(('addright',))


class Command_delright(TqlCommand):
    '''Delete account right'''

    def __init__(self, cli, argv0):
        TqlCommand.__init__(self, cli, argv0)
        self.tql_filter += "&a&r=cli"
        self.set_usage('''%prog [options] <tql> <index>

<index> * means all''')

    def __call__(self, argv):
        # argv check
        self.parse_args(argv)
        if len(self.args) != 2:
            raise cmdBadArgument()
        # building list of index
        try:
            l = [ int(x) for x in self.args[1:] if x != "*" ]
        except ValueError as e:
            raise cmdBadArgument("Indexes must be numbers")
        # if all is detected
        if "*" in self.args[1:]:
            self.rpccall("delright", self.args[0], None)
        else:
            for index in l:
                self.rpccall("delright", self.args[0], index)

    def remote_functions(self):
        return set(('delright',))