import os
import time
import dialog
from modules.sitegrouphosttools import SiteGroupHostTools
from modules.groups.group import Group
from modules.groups.groupform import GroupForm
from modules.groups.groupmenu import GroupMenu
from modules.sitegrouphosttools import get_group_members

class GroupListMenu(SiteGroupHostTools):

    def __init__(self):
        self.d = dialog.Dialog(dialog="dialog")
        self.storage_path = os.path.expanduser("~/LidskjalvData")
        self.g = Group()
        self.gf = GroupForm()
        self.gm = GroupMenu()
        self.sght = SiteGroupHostTools()

    def show_menu(self, site):
        while True:
            menu = self.build_menu(site)
            sz = os.get_terminal_size()
            s = "Select a group or action in site '%s'" % site
            code, tag = self.d.menu(s,
                                    title="Site: '%s' - Groups menu" % site,
                                    height=sz.lines - 5,
                                    width=sz.columns - 8,
                                    menu_height=sz.lines - 15,
                                    backtitle="Lidskjalv",
                                    choices=menu)
            if code == self.d.OK:
                r = self.process_menu(site, tag)
                if r is None:
                    break
            else:
                break

    def build_menu(self, site):
        sp = self.storage_path
        if not self.g.group_exist(site, 'Cisco Switches'):
            self.g.create_group(site,
                                'Cisco Switches',
                                "",
                                int(time.time()),
                                [])
        if not self.g.group_exist(site, 'MAC exempt'):
            self.g.create_group(site,
                                'MAC exempt',
                                "",
                                int(time.time()),
                                [])
        if not self.g.group_exist(site, 'Nagios'):
            self.g.create_group(site,
                                'Nagios',
                                "",
                                int(time.time()),
                                [])
        listofgroups = self.g.list_of_groups_by_name(site)
        menu = []
        menu.append(["AG", "Add group"])
        menu.append(["Q", "Quit"])
        menu.append(["", " "])
        for group in listofgroups:
            memberslist = get_group_members(sp, site, group)
            ml = len(memberslist)
            gd = self.g.get_group_description(site, group)
            d = "%s Member(s) - %s" % (str(ml).rjust(3), gd)
            menu.append([group, d])
        return menu

    def process_menu(self, site, tag):
        if tag == "Q":
            return None
        if tag == "AG":
            self.gf.group_form(site, None)
        if tag in self.g.list_of_groups(site):
            self.gm.show_menu(site, tag)
        return True
