#!/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")

    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)
            # update tql if mode
            if not self.options.raw:
                tql += "&a"
        # ask server
        al = self.rpccall("rights", tql, _direct=True, _status=False)
        # display answer
        for (a, rl) in al.items():
            self.printer.out("%srights of %s%s"%(color["lblue"], a, color["reset"]))
            for i,r in enumerate(rl):
                tags = " ".join([ "%s%s:%s%s"%(color["green"], t, color["reset"], v) for (t,v) in r.items() ])
                self.printer.out("[%s] %s"%(i,tags))


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[5] = int(self.args[5])
        else:
            raise cmdBadArgument()
        # rpc call
        self.rpccall("addright",
                    self.args[0],
                    self.args[1],
                    self.args[2],
                    self.args[3],
                    self.args[4])

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
        l = self.args[1:]
        # if all is detected
        if "*" in l:
            self.rpccall("delright", self.args[0], None)
        else:
            for index in l:
                self.rpccall("delright", self.args[0], index)