#!/usr/bin/env python

import sys
import os
import json
import datetime
from optparse import OptionParser
import PyZenity

CLIENTS_PATH = os.path.join(os.path.expanduser('~'), 'share', 'Clients')
CLIENTS_FILE = os.path.join(CLIENTS_PATH, "Clients.json")
CLIENT_ACTIONS = [
    ("Web", "Exec /usr/bin/google-chrome http://%(IP)s/"),
    ("SSH", "Exec /usr/bin/gnome-terminal --profile=bastion --disable-factory -e 'ssh -t ghislain@bastion ssh -A mca@%(IP)s'"),
    ("SSH (root)", "Exec /usr/bin/gnome-terminal --profile=bastion --disable-factory -e 'ssh -t ghislain@bastion ssh -A root@%(IP)s'"),
    ("Git status", "Exec /usr/bin/gnome-terminal --profile=bastion --disable-factory -e 'ssh -t ghislain@bastion ssh -A mca@%(IP)s \"GIT_DIR=/home/mca/MCA3/.git GIT_WORK_TREE=/home/mca/MCA3/ git status; read\"'"),
    ]

class MenuMaker(object):

    def show_date(self):
        return """Entry = "%s" { Actions = "Exec /home/gl/bin/myxclock" }""" % (datetime.datetime.now(),)

    def add_client(self, parent):
        with open(CLIENTS_FILE) as fp:
            data = json.load(fp)
        for item in data:
            if item["nom"] == parent and "liste" in item:
                new_name = PyZenity.GetText(text="nom")
                new_ip = PyZenity.GetText(text="IP", entry_text="10.")
                item["liste"].append({"nom":new_name, "IP": new_ip})
                break
        with open(CLIENTS_FILE, "w") as fp:
            json.dump(data, fp)

    def show_clients(self):
        result = []
        with open(CLIENTS_FILE) as fp:
            data = json.load(fp)
            for item in data:
                result.append(self.make_client_menu(item))
        return "\n".join(result)

    def make_client_menu(self, item):
        result = []
        if "liste" in item:
            result.append("""Submenu = "%(nom)s" {""" % item)
            for subitem in item["liste"]:
                result.append(self.make_client_menu(subitem))
            result.append("""Separator {}""")
            result.append("""Entry = "Ajout" {Actions = "Exec /home/gl/bin/MonMenu --add_client='%(nom)s'"}""" % item)
            result.append("""}""")
        else:
            result.append("""Submenu = "%(nom)s" {""" % item)
            for action_name, action_script in CLIENT_ACTIONS:
                result.append("""  Entry = "%s" {Actions = "%s" }""" % (action_name, action_script % item))
            result.append("""}""")
        return "\n".join(result)

    def make_menu(self):
        print "Dynamic {"
        print self.show_clients()
        print "Separator {}"
        print self.show_date()
        print "}"

if __name__ == "__main__":

    parser = OptionParser()
    parser.add_option("--add_client",
        dest="add_client",
        help="Add a client")
    options = parser.parse_args()[0]

    mm = MenuMaker()
    if options.add_client:
        mm.add_client(options.add_client)
    else:
        mm.make_menu()

# print """

# Dynamic {
#   Entry = "" { Actions = "Exec xterm" }
#   Entry = "xclock" { Actions = "Exec xclock" }
#   }
# }
# """
