#!/usr/bin/env python
# -*- coding: utf8



import faster_module_path

import faster.new_ui.config.config_model as config_model
from faster.new_ui.config.config_presenter import ConfigPresenter
from faster.new_ui.config.config_options_ttk_view import ConfigOptionsTtkView
from faster.new_ui.config.config_element_tree_ttk_view import ConfigElementTreeTtkView
from faster.new_ui.config.config_command_panel_ttk_view import ConfigCommandPanelTtkView

from faster.new_ui.hardware_selection_dialog import HardwareSelectionDialog

from faster.gui.resource_loader import IMAGE_PATH

import faster.new_ui.config.faster_setup_exceptions

import webbrowser

import argparse
import os

try:
  # python 2
  import tkinter as tk
  import tkinter.ttk
  from tkinter import messagebox as messagebox
  #print('python')
except:
  # python 3
  #print('python3')
  try:
    import tkinter as tk
    import tkinter.ttk as ttk
    from tkinter import messagebox
  except:
    print('error importing tkinter or ttk')
    raise

class ConfigApp(tkinter.ttk.Frame):

  EXIT_OK	= 0
  EXIT_ERROR	= 1

  def __init__(self, master):

    self.running = False
    tkinter.ttk.Frame.__init__(self, master)
    self.exit_status = ConfigApp.EXIT_ERROR
    self.master.protocol("WM_DELETE_WINDOW", self.user_request_quit)

  def start(self):
    existing_config = config_model.read_from_disk()

    if existing_config:
      # found and loaded existing config
      try:
        self.load_existing_config(existing_config)
      except Exception as ex:
        print(ex)
      else:
        self.running = True
    else:
      # start new config
      self.ask_config_type()

    #if self.running:
    #  self.config_m.set_lpc_mode(lpc_mode)

  def user_request_quit(self, event=None):
    """
    """
    # TBD lose changes ?
    answer = self.check_save(title='Quitting...', message='Save changes before exit ?')

    if answer is None:
      # cancel
      return

    if answer is True:
      can_be_saved, message = self.config_p.can_save()
      if not can_be_saved:
        response = messagebox.askyesno('Undefined configration', message + '\n\nYour configuration can not be saved at this point. Exit anyway ?', icon='warning')
        if response:
          # yes, really quit now
          self.exit_ok()
      else:
        #print ("==> Configuration files has been saved")
        if not self.user_request_save():
          # saving failed, do not quit
          return
        else:
          self.exit_ok()
    else:
      # user does not want to save
      self.exit_ok()

  def exit_ok(self):
    self.exit_status = ConfigApp.EXIT_OK
    self.quit()

  def user_request_save(self):
    """
    """
    success, message = self.config_p.save_config()
    #if success and not message:
    #  message = 'Configuration saved.\nRHB PID catalog in sample.pid'
    if success:
      if messagebox.askyesno('RHB configuration', 'Write RHB configuration based on your setup ?', icon='question'):
        import py_faster_rhb
        from py_faster_rhb import rhb
        self.rhb = rhb ()
    else:
      messagebox.showinfo('Saving failed !\n\n', message)
    return success

  def user_request_new_amc(self):
    """
    """
    self.config_p.event_user_add_motherboard()

  def user_request_detect_motherboards(self):
    """
    """
    self.config_p.event_user_detect_motherboards()

  def check_save(self, title, message):
    return messagebox.askyesnocancel(title, message, icon='warning')

  def clear_ui(self):
    self.ui_frame.pack_forget()

  def draw_ui(self):
    """
    requires existence of model and presenter
    """
    self.ui_frame = tkinter.ttk.Frame(self)
    self.ui_frame.pack(expand=tk.YES, fill=tk.BOTH)
    f = tkinter.ttk.Frame(self.ui_frame)
    f.pack(expand=tk.NO, fill=tk.X)

    v1 = ConfigOptionsTtkView(f, config_presenter=self.config_p)
    v1.pack(expand=tk.YES, fill=tk.X, side=tk.LEFT, padx='2mm', pady='2mm')
    self.logo_faster = tk.PhotoImage(file=os.path.join (IMAGE_PATH, 'logo_faster_h80.gif'))
    self.logo_lpc = tk.PhotoImage(file=os.path.join (IMAGE_PATH, 'logo_lpc_couleur_fond_blanc_h80.gif'))
    tkinter.ttk.Label(f, image=(self.logo_lpc)).pack(side=tk.RIGHT)
    tkinter.ttk.Label(f, image=(self.logo_faster)).pack(side=tk.RIGHT)

    v2 = ConfigElementTreeTtkView(self.ui_frame, config_presenter=self.config_p)
    v2.pack(expand=tk.YES, fill=tk.BOTH)
    
    tkinter.ttk.Label(self.ui_frame, text='Use CTRL/SHIFT + right click to select multiple channels', relief=tk.SUNKEN, anchor=tk.CENTER).pack(fill=tk.X, expand=tk.YES)

    toolbar = tkinter.ttk.Frame(self.ui_frame, border=2, relief=tk.RIDGE)
    if self.config_m.config_type == 0:
      add_amc_board_b = tkinter.ttk.Button(toolbar, text='Add a new\nAMC motherboard', command=self.user_request_new_amc)
      add_amc_board_b.pack(side=tk.LEFT, expand=tk.NO, padx='2mm', pady='1mm')
    #temporary_save_b = ttk.Button(toolbar, text='TEST\nSAVE CONFIG', command=self.user_request_save)
    #temporary_save_b.pack(side=tk.RIGHT, expand=tk.NO, padx='2mm', pady='1mm')

      detect_amc_board_b = tkinter.ttk.Button(toolbar, text='Detect\nAMC motherboards', command=self.user_request_detect_motherboards)
      detect_amc_board_b.pack(side=tk.LEFT, expand=tk.NO, padx='2mm', pady='1mm')

    if toolbar.winfo_children():
      toolbar.pack(expand=tk.NO, fill=tk.X, padx='2mm', pady='2mm')

    v3 = ConfigCommandPanelTtkView(self.ui_frame, config_presenter=self.config_p, title='command panels', edit_mode=True)
    v3.pack(expand=tk.NO, fill=tk.BOTH)

    url = 'http://faster.in2p3.fr/index.php/documentation'
    tk.Button(self, text='Click here to open hardware modules documentation in your browser', command=lambda: webbrowser.open_new(url)).pack(expand=tk.NO, fill=tk.X)


  def fill_startup_config(self, config_type):
    # build a default startup config
    if self.config_m.config_type != 0:
      # not using AMC => using SYROCO or NIM, single board configuration : user can not add a board, let's do it for him
      self.config_p.event_add_motherboard()

    default_channel_group = self.config_p.event_add_command_panel()
    self.config_p.event_add_channel_group_request(default_channel_group, 'Channels')


  def ask_config_type(self):
    d = HardwareSelectionDialog()
    if d.value is not None:
      self.new(d.value)
      self.running = True
    else:
      self.exit_status = ConfigApp.EXIT_OK
      self.running = False


  def new(self, config_type=None):
    self.config_m = config_model.ConfigModel(config_type)
    self.config_p = ConfigPresenter(config_model=self.config_m)
    self.config_m.new_tree()
    self.draw_ui()
    self.fill_startup_config(config_type)


  def load_existing_config(self, config):
    self.config_m = config
    self.config_p = ConfigPresenter(config_model=self.config_m)

    self.draw_ui()
    self.config_p.draw_all_element_tree_nodes()

    #default_channel_group = self.config_p.event_add_command_panel()
    #self.config_p.event_add_channel_group_request(default_channel_group, 'Channels')

    self.config_p.draw_all_command_panels()

if __name__ == '__main__':
  import sys
  #print(sys.version)

  root = tk.Tk()
  root.withdraw()
  root.title('FASTER setup GUI')

  parser = argparse.ArgumentParser(prog='faster_setup_gui')
  args = parser.parse_args()

  app = ConfigApp(master=root)
  app.pack(fill=tk.BOTH, expand=tk.YES)
  app.start()
  if app.running:
    root.deiconify()
    root.mainloop()
  #print('==> exit')
  if app.exit_status != ConfigApp.EXIT_OK:
      print('error', app.exit_status)
  root.destroy()

  sys.exit(app.exit_status)
