#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# generated by wxGlade 0.9.3 on Sat Feb  1 06:42:01 2020
#

import wx

from Kernel import Module, STATE_UNKNOWN
from icons import icons8_administrative_tools_50, icons8_down, icons8up, icons8_plus_50, icons8_trash_50

_ = wx.GetTranslation


class DeviceManager(wx.Frame, Module):
    def __init__(self, *args, **kwds):
        # begin wxGlade: DeviceManager.__init__
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE | wx.FRAME_TOOL_WINDOW | wx.STAY_ON_TOP
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((707, 337))
        self.devices_list = wx.ListCtrl(self, wx.ID_ANY, style=wx.LC_HRULES | wx.LC_REPORT | wx.LC_VRULES)
        self.new_device_button = wx.BitmapButton(self, wx.ID_ANY, icons8_plus_50.GetBitmap())
        self.remove_device_button = wx.BitmapButton(self, wx.ID_ANY, icons8_trash_50.GetBitmap())
        self.device_properties_button = wx.BitmapButton(self, wx.ID_ANY, icons8_administrative_tools_50.GetBitmap())
        self.move_item_up_button = wx.BitmapButton(self, wx.ID_ANY, icons8up.GetBitmap())
        self.move_item_down_button = wx.BitmapButton(self, wx.ID_ANY, icons8_down.GetBitmap())

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_LIST_BEGIN_DRAG, self.on_list_drag, self.devices_list)
        self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.on_list_item_activated, self.devices_list)
        self.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.on_list_right_click, self.devices_list)
        self.Bind(wx.EVT_BUTTON, self.on_button_new, self.new_device_button)
        self.Bind(wx.EVT_BUTTON, self.on_button_remove, self.remove_device_button)
        self.Bind(wx.EVT_BUTTON, self.on_button_properties, self.device_properties_button)
        self.Bind(wx.EVT_BUTTON, self.on_button_up, self.move_item_up_button)
        self.Bind(wx.EVT_BUTTON, self.on_button_down, self.move_item_down_button)
        # end wxGlade

        self.Bind(wx.EVT_CLOSE, self.on_close, self)

    def initialize(self):
        self.device.close('window', self.name)
        self.Show()
        self.device.setting(str, 'list_devices', '')
        self.refresh_device_list()

    def shutdown(self,  channel):
        self.Close()
        item = self.devices_list.GetFirstSelected()
        if item != -1:
            uid = self.devices_list.GetItem(item).Text
            self.device.device_primary = uid

    def on_close(self, event):
        self.device.remove('window', self.name)
        event.Skip()  # Call destroy as regular.

    def __set_properties(self):
        # begin wxGlade: DeviceManager.__set_properties
        self.SetTitle("Device Manager")
        self.devices_list.SetFont(wx.Font(13, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, 0, "Segoe UI"))
        self.devices_list.AppendColumn(_("Id"), format=wx.LIST_FORMAT_LEFT, width=72)
        self.devices_list.AppendColumn(_("Driver"), format=wx.LIST_FORMAT_LEFT, width=119)
        self.devices_list.AppendColumn(_("State"), format=wx.LIST_FORMAT_LEFT, width=127)
        self.devices_list.AppendColumn(_("Location"), format=wx.LIST_FORMAT_LEFT, width=258)
        self.devices_list.AppendColumn(_("Boot"), format=wx.LIST_FORMAT_LEFT, width=51)
        self.new_device_button.SetToolTip(_("Add a new device"))
        self.new_device_button.SetSize(self.new_device_button.GetBestSize())
        self.remove_device_button.SetToolTip(_("Remove selected device"))
        self.remove_device_button.SetSize(self.remove_device_button.GetBestSize())
        self.device_properties_button.SetToolTip(_("View Device Properties"))
        self.device_properties_button.SetSize(self.device_properties_button.GetBestSize())
        self.move_item_up_button.SetToolTip(_("Move device up"))
        self.move_item_up_button.SetSize(self.move_item_up_button.GetBestSize())
        self.move_item_down_button.SetToolTip(_("Move device down"))
        self.move_item_down_button.SetSize(self.move_item_down_button.GetBestSize())
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: DeviceManager.__do_layout
        main_sizer = wx.BoxSizer(wx.HORIZONTAL)
        button_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(self.devices_list, 1, wx.EXPAND, 0)
        button_sizer.Add(self.new_device_button, 0, 0, 0)
        button_sizer.Add(self.remove_device_button, 0, 0, 0)
        button_sizer.Add(self.device_properties_button, 0, 0, 0)
        # button_sizer.Add(self.move_item_up_button, 0, 0, 0)
        # button_sizer.Add(self.move_item_down_button, 0, 0, 0)
        main_sizer.Add(button_sizer, 0, wx.EXPAND, 0)
        self.SetSizer(main_sizer)
        self.Layout()
        # end wxGlade

    def refresh_device_list(self):
        devices = self.device.list_devices
        self.devices_list.DeleteAllItems()
        i = 0
        for device in devices.split(';'):
            try:
                d = int(device)
            except ValueError:
                return
            device_name = self.device.read_persistent(str, 'device_name', 'Lhystudios', uid=d)
            autoboot = self.device.read_persistent(bool, 'autoboot', True, uid=d)
            location_name = self.device.read_persistent(str, 'location_name', 'Unknown', uid=d)
            try:
                device_obj = self.device.instances['device'][device]
                state = device_obj.state
            except KeyError:
                state = -1
            m = self.devices_list.InsertItem(i, str(d))
            if m != -1:
                self.devices_list.SetItem(m, 1, str(device_name))
                self.devices_list.SetItem(m, 2, str(state))
                self.devices_list.SetItem(m, 3, str(location_name))
                self.devices_list.SetItem(m, 4, str(autoboot))
            i += 1

    def on_list_drag(self, event):  # wxGlade: DeviceManager.<event_handler>
        pass

    def on_list_right_click(self, event):  # wxGlade: DeviceManager.<event_handler>
        uid = event.GetLabel()
        toggled_autoboot = not self.device.read_persistent(bool, 'autoboot', True, int(uid))
        self.device.write_persistent('autoboot', toggled_autoboot, int(uid))
        try:
            # If the device is booted, change autoboot there too.
            device_obj = self.device.instances['device'][str(uid)]
            device_obj.autoboot = toggled_autoboot
        except KeyError:
            pass
        self.refresh_device_list()

    def on_list_item_activated(self, event):  # wxGlade: DeviceManager.<event_handler>
        uid = event.GetLabel()
        try:
            device = self.device.instances['device'][uid]
        except KeyError:
            device_name = self.device.read_persistent(str, 'device_name', 'Lhystudios', uid)
            device = self.device.open('device', device_name, root=self.device, uid=int(uid), instance_name=str(uid))
        if device.state == STATE_UNKNOWN:
            device.open('window', "MeerK40t", None, -1, "")
            device.boot()
            self.Close()
        else:
            dlg = wx.MessageDialog(None, _("That device already booted."),
                                   _("Cannot Boot Selected Device"), wx.OK | wx.ICON_WARNING)
            result = dlg.ShowModal()
            dlg.Destroy()

    def on_button_new(self, event):  # wxGlade: DeviceManager.<event_handler>
        names = [name for name in self.device.registered['device']]
        dlg = wx.SingleChoiceDialog(None, _('What type of device is being added?'), _('Device Type'), names)
        dlg.SetSelection(0)
        if dlg.ShowModal() == wx.ID_OK:
            device_type = dlg.GetSelection()
            device_type = names[device_type]
        else:
            dlg.Destroy()
            return
        dlg.Destroy()
        device_uid = 0
        while device_uid <= 100:
            device_uid += 1
            device_match = self.device.read_persistent(str, 'device_name', default='', uid=device_uid)
            if device_match == '':
                break
        self.device.write_persistent('device_name', device_type, uid=device_uid)
        self.device.write_persistent('autoboot', True, uid=device_uid)
        devices = [d for d in self.device.list_devices.split(';') if d != '']
        devices.append(str(device_uid))
        self.device.list_devices = ';'.join(devices)
        self.device.write_persistent('list_devices', self.device.list_devices)
        self.refresh_device_list()

    def on_button_remove(self, event):  # wxGlade: DeviceManager.<event_handler>
        item = self.devices_list.GetFirstSelected()
        uid = self.devices_list.GetItem(item).Text
        self.device.list_devices = ';'.join([d for d in self.device.list_devices.split(';') if d != uid])
        try:
            device = self.device.instances['device'][uid]
            del self.device.instances['device'][uid]
            device.instances['module']['MeerK40t'].Close()
        except KeyError:
            pass
        except AttributeError:
            pass

        self.refresh_device_list()

    def on_button_properties(self, event):  # wxGlade: DeviceManager.<event_handler>
        item = self.devices_list.GetFirstSelected()
        uid = self.devices_list.GetItem(item).Text
        dev = self.device.device_root.instances['device'][uid]
        dev.open('window', "Preferences", None, -1, "")

    def on_button_up(self, event):  # wxGlade: DeviceManager.<event_handler>
        print("Event handler 'on_button_up' not implemented!")
        event.Skip()

    def on_button_down(self, event):  # wxGlade: DeviceManager.<event_handler>
        print("Event handler 'on_button_down' not implemented!")
        event.Skip()