"""Subclass of mainFrame, which is generated by wxFormBuilder."""

import wx
import wx.py
import wx.py.dispatcher as dp
import wx.adv
import matplotlib.pyplot as plt
import aui2 as aui
from .frameplus import FramePlus
from .demo_panel import DemoPanel

class MainFrame(FramePlus):

    ID_VM_RENAME = wx.NewIdRef()
    ID_CONTACT = wx.NewIdRef()

    def __init__(self, parent, **kwargs):
        FramePlus.__init__(self,
                           parent,
                           title='MPLPanel demo',
                           size=wx.Size(800, 600),
                           style=wx.DEFAULT_FRAME_STYLE | wx.TAB_TRAVERSAL)
        self.InitMenu()

        agw_flags = (self._mgr.GetAGWFlags()
                              | aui.AUI_MGR_ALLOW_ACTIVE_PANE
                              | aui.AUI_MGR_USE_NATIVE_MINIFRAMES
                              | aui.AUI_MGR_LIVE_RESIZE)

        if wx.Platform != '__WXMSW__':
            agw_flags |= aui.AUI_MGR_SMOOTH_DOCKING

        self._mgr.SetAGWFlags(agw_flags)

        # status bar
        self.statusbar = wx.StatusBar(self)
        self.SetStatusBar(self.statusbar)
        self.statusbar_width = [-1]
        self.statusbar.SetStatusWidths(self.statusbar_width)

        # persistent configuration
        self.closing = False

        self.Bind(wx.EVT_ACTIVATE, self.OnActivate)
        self.Bind(aui.EVT_AUI_PANE_ACTIVATED, self.OnPaneActivated)
        self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)

        DemoPanel.Initialize(self)

        # add shell
        ns = {}
        ns['wx'] = wx
        ns['app'] = wx.GetApp()
        ns['frame'] = self
        self.shell = wx.py.shell.Shell(self, -1, locals=ns)

        pane_shell = aui.AuiPaneInfo().Name("Shell").Caption("Shell").Bottom()\
                          .BestSize((300, 300)).DestroyOnClose(False).Snappable()\
                          .Dockable().MinimizeButton(True).MaximizeButton(True)\
                          .Row(-1).Bottom().Position(99)
        self.RunCommand('import matplotlib.pyplot as plt', verbose=False)
        self.RunCommand('import pickle', verbose=False)
        dp.connect(self.RunCommand, 'shell.run')

        self.AddPanel(self.shell, 'Shell')
        self._mgr.Update()
        plt.figure()

    def RunCommand(self, command, prompt=True, verbose=True, history=False):
        if verbose:
            self.shell.write(command)

        self.shell.push(command, silent=not prompt)

    def InitMenu(self):
        """initialize the menubar"""
        menubar = wx.MenuBar()
        self.SetMenuBar(menubar)

        self.AddMenu('&File:New Figure', id=wx.ID_NEW, autocreate=True)
        self.AddMenu('&File:Sep', kind="Separator")
        self.AddMenu('&File:&Quit', id=wx.ID_CLOSE)

        # Connect Events
        self.Bind(wx.EVT_MENU, self.OnFileQuit, id=wx.ID_CLOSE)
        self.Bind(wx.EVT_MENU, self.OnFileNew, id=wx.ID_NEW)

    def OnClose(self, event):
        """close the main program"""
        dp.send('frame.closing', event=event)
        if event.GetVeto():
            return
        self.closing = True
        dp.send('frame.exiting')
        sz = self.GetSize()
        dp.send('frame.exit')
        super().OnClose(event)

    def ShowStatusText(self, text, index=0, width=-1):
        """set the status text"""
        if index >= len(self.statusbar_width):
            exd = [0] * (index + 1 - len(self.statusbar_width))
            self.statusbar_width.extend(exd)
            self.statusbar.SetFieldsCount(index + 1)
        if self.statusbar_width[index] < width:
            self.statusbar_width[index] = width
            self.statusbar.SetStatusWidths(self.statusbar_width)
        self.statusbar.SetStatusText(text, index)

    def OnActivate(self, event):
        if not self.closing:
            dp.send('frame.activate', activate=event.GetActive())
        event.Skip()

    def OnPaneActivated(self, event):
        """notify the window managers that the panel is activated"""
        if self.closing:
            return
        pane = event.GetPane()
        if isinstance(pane, aui.auibook.AuiNotebook):
            window = pane.GetCurrentPage()
        else:
            window = pane

        dp.send('frame.activate_panel', pane=window)

    def OnPaneClose(self, event):
        """notify the window managers that the pane is closing"""
        if self.closing:
            return
        dp.send('frame.close_pane', event=event)

    # Handlers for mainFrame events.
    def OnFileQuit(self, event):
        """close the program"""
        self.Close(True)

    def OnFileNew(self, event):
        plt.figure()
