#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright (C) 2015 Rod Engerstad


import tkinter as tk
import tkinter.messagebox
import os
import subprocess
import shutil

from pzl_lib import PzlG
from pzl_lib import SGImage
from pzl_lib import MenuItem
from pzl_lib import Menu

class View(tk.Toplevel):
    """
    Stick blobs on the screen and respond to callbacks
    """

    def __init__(self, master, settings):
        tk.Toplevel.__init__(self, master)
        self.protocol('WM_DELETE_WINDOW', self.master.destroy)
        self.title(string='pzl_launcher')
        self.resizable(False, False)
        self.master = master
        self.settings = settings
        self.control_frame = None
        self.outer_frame = None
        self.menu_bar = None
        self.images = SGImage()
        self.grid_widgets = []
        self.make_frames(self)

        self.menu = Menu(self.settings, self.menu_bar, self.images.file)
        self.label = tk.Label(self.menu_bar, image=self.images.pzl_label)
        self.label.grid(row=0, column=1)

    def make_frames(self, root):
        bg = self.settings.grey
        self.outer_frame = tk.Frame(root, bg=bg)
        self.outer_frame.grid()
        self.control_frame = tk.Frame(self.outer_frame,
                bd=2, bg=bg, relief='raised')
        self.control_frame.grid(row=0, column=0, sticky='W')
        self.menu_bar = tk.Frame(self.control_frame, relief='raised',
                                bd=2, bg=bg)
        self.menu_bar.grid(row=0, column=0, sticky='W')


    def add_menu_callback(self, func):
        self.menu.callback_func = func


    def about(self):
        my_title = self.settings.title
        my_text = PzlG.about_text
        tkinter.messagebox.showinfo(my_title, detail=my_text)


    def help(self):
        my_title = self.settings.title
        my_text = self.settings.help_text
        tkinter.messagebox.showinfo(my_title, detail=my_text)


    def uninstall(self):
        my_title = _('Uninstall all pzl')
        my_text = _('Are you sure you want to uninstall all pzl programs and data?')

        if tkinter.messagebox.askyesno(my_title, my_text):
            shutil.rmtree(PzlG.path_name)


class Settings(object):
    """
    Set and update all user controlled values and most other constants
    For globals in code which does not have access to Settings use Sgg.
    """

    nonexclusive = 'N'

    def __init__(self):
        self.menu = {}
        self.program_list = PzlG.get_program_list()
        self.gray = '#C0C0C0'
        self.grey = '#dfdfdf'
        self.green = '#82c026'
        self.white = '#ffffff'
        self.black = '#000000'
        self.red = '#ff0000'
        self.dic = {}
        self.find_programs()
        self.menu_items = []
        self.load_menus()
        self.count = len(self.menu_items)
        self.title = PzlG.app_name + ' ' + PzlG.version + '          '
        self.help_text = None
        self.make_help()

    def make_help(self):
        self.help_text = _("The program consists of a menu listing the currently installed pzl games. Use the menu to select a game and it will launch in a separate window. Only one game can be used at a time. The uninstall option will delete the .pzl directory and all its contents!")


    def find_programs(self):
        sep = os.sep
        ext = '.py'
        if PzlG.this_os == 'windows':
            ext = '.pyw'
        for program in self.program_list:
            path_name = PzlG.PROGRAMS_path + sep + program + ext
            try:
                junk = open(path_name, 'r')
                self.menu[program] = path_name
            except IOError:
                pass

    def load_menus(self):
        for program in self.program_list:
            self.menu_items.append(MenuItem(program, '', '', '', program))

        self.menu_items.append(MenuItem(
                _('Help'),
                '',
                '',
                '',
                'help'
                ))
        self.menu_items.append(MenuItem(
                _('About'),
                '',
                '',
                '',
                'about'
                ))
        self.menu_items.append(MenuItem(
                _('Uninstall all pzl'),
                '',
                '',
                '',
                'uninstall'
                ))

class Controller(object):
    """
    Set up and control
    """

    def __init__(self, root):
        self.settings = Settings()
        self.master = root
        self.view = View(root, self.settings)
        self.add_callbacks()
        self.start_game(None)


    def start_game(self, name):
        if name is not None:
            if PzlG.PY3:
                program = "python3"
            else:
                program = "python"
            if PzlG.this_os == 'windows':
                if PzlG.PY3:
                    program = "pythonw3"
                else:
                    program = "pythonw"
            arg1 = self.settings.menu[name]
            arg2 = " &"
            subprocess.call([program, arg1, arg2])

    def add_callbacks(self):
        self.view.add_menu_callback(self.service_menu)



    def service_menu(self, *args):
        """
        Respond to menu choices
        """
        strargs = ''
        for item in args:
            strargs += ' ' + item
        PzlG.logger.logger.info("service_menu " + strargs)
        name = args[0]
        if name == 'about':
            self.view.about()
        elif name == 'help':
            self.view.help()
        elif name == 'uninstall':
            self.view.uninstall()
        else:
            self.start_game(name)


INITIALISE = PzlG()
if __name__ == '__main__':
    try:
        ROOT = tk.Tk()
        ROOT.withdraw()
        APP = Controller(ROOT)
        ROOT.mainloop()
        PzlG.logger.logger.info("Stop program")
    except:
        PzlG.logger.logger.info("Failure!")
        PzlG.logger.logger.exception("Unhandled exception during main")
