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

'''
CloudControl list command
'''

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

class Command_list(TqlCommand):
    '''List objects'''

    def __init__(self, cli, argv0):
        TqlCommand.__init__(self, cli, argv0)
        self.set_usage("%prog [options] [tql]")
        self.add_option("-t", action="store_true", dest="table",
                        help="column aligment display")
        self.add_option("-l", action="store_true", dest="align",
                        help="line aligment display")
        self.remove_option("--quiet")
        self.remove_option("--direct")

    def __call__(self, argv):
        self.parse_args(argv)
        if len(self.args) == 0:
            self.args.append("")
        objs = self.rpccall("list", str.join("", self.args), _status=False, _direct=True)
        if len(objs) == 0:
            return
        if self.options.align:
            self.list_align(objs)
        elif self.options.table:
            self.list_table(objs)
        else:
            self.print_objects(objs)

    def list_align(self, objs):
        '''Listing line aligned'''
        # get max size by tag
        tags = dict()
        for o in objs:
            for (t, v) in o:
                tags[t] = max(len(self.tdr(t, v)), tags.get(t, len(t)))
        # dislay each object by line
        for o in objs:
            # show others tags
            line = str()
            for (tagname,tagvalue) in o:
                line += "%s%s:%s%s"%(self.tdtc(tagname),
                                     tagname,
                                     self.tdc(tagname),
                                     self.tdr(tagname, tagvalue).ljust(tags[tagname] + 1))
            self.printer.out("%s%s"%(line, color["reset"]))

    def list_table(self, objs):
        '''Listing table style'''
        # get max size by tag
        tags = dict()
        for o in objs:
            for (t,v) in o:
                tags[t] = max(len(self.tdr(t, v)), tags.get(t, len(t)))
        # print title
        for t,v in tags.items():
            self.printer.out(self.tdtc(t), nl="")
            self.printer.out(t.ljust(v), nl=" ")
        self.printer.out(color["reset"])
        # print obj
        for obj in objs:
            obj = dict(obj)
            # print others tags
            for (t, v) in tags.items():
                self.printer.out(self.tdc(t), nl="")
                self.printer.out(self.tdr(t, obj.get(t, u"")).ljust(v) ,nl=" ")
            self.printer.out(color["reset"])