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

import wx
import wx.stc
from ctx import theContext as context
import app
import tran
from app.ui.pane import BasePane
from activity.files.ui import ui as ui
from activity.models.ui import ui as amui

CLOSE_PANE_ID = wx.ID_HIGHEST + 100


# Implementing FilePane
class FilePane(BasePane, ui.FilePane):
    """Implements code editor"""
    def __init__(self, parent, mainframe, fileobj):
        """Intialization of method editor"""
        super(FilePane, self).__init__(parent)
        self._parent = parent
        self._mainframe = mainframe
        self._object = fileobj
        self._types = dict([(x._name, x) for x in fileobj.project.types])
        self._defaulBkColor = self.GetBackgroundColour()
        self.m_editor.SetText(fileobj.GetText())
        self.m_editor.HandleBreakpoints(fileobj.breakpoints)
        self.m_editor.HandleBookmarks(fileobj.bookmarks)
        self.m_editor.EnableBreakpoints(True)
        self.m_editor.EnableBookmarks(True)
        self.m_editor.Initialize(self._types)
        self.m_editor.SetReadOnly(fileobj._readOnly)
        self.Layout()
        wx.stc.EVT_STC_CHANGE(self.m_editor, self.m_editor.GetId(),
            self.OnEditorChange)
        frame = context.frame
        self.Bind(wx.EVT_MENU, handler=frame.CloseCurrentDocPane, id=CLOSE_PANE_ID)
        self.Bind(wx.EVT_MENU, handler=self.OnDelete, id=frame.delete.GetId())
        self.Bind(wx.EVT_MENU, handler=self.OnSave, id=frame.saveProject.GetId())
        self.Bind(wx.EVT_UPDATE_UI, handler=self.OnUpdateSave, id=frame.saveProject.GetId())
        aTable = wx.AcceleratorTable([
            wx.AcceleratorEntry(wx.ACCEL_NORMAL, wx.WXK_DELETE, frame.delete.GetId()),
            wx.AcceleratorEntry(wx.ACCEL_ALT | wx.ACCEL_CTRL, ord('F'), amui.ID_TOGGLE_FULLSCREEN),
            wx.AcceleratorEntry(wx.ACCEL_CTRL, ord('W'), CLOSE_PANE_ID)
        ])
        self.SetAcceleratorTable(aTable)

    def Refresh(self):
        """Update editor from external changes (like undo/redo)"""
        oldText = self.m_editor.GetText()
        newText = self._object.GetText()
        if oldText == newText:
            return
        line = self.m_editor.GetFirstVisibleLine()
        pos = self.m_editor.GetCurrentPos()
        self.m_editor.Freeze()
        self.m_editor.SetText(self._object.GetText())
        self.m_editor.SetModified(False)
        try:
            self.m_editor.SetFirstVisibleLine(line)
            self.m_editor.SetCurrentPos(pos)
        except:
            pass
        self.m_editor.Thaw()

    def OnEditorChange(self, event):
        """Called when editor status change"""
        if self.m_editor.GetModify():
            self.SetBackgroundColour(wx.LIGHT_GREY)
        else:
            self.SetBackgroundColour(self._defaulBkColor)

    def GotoLine(self, line, select=False):
        """Called for goto to line"""
        self.m_editor.GotoLine(line, select)

    @tran.TransactionalMethod('modify file {}')
    def Commit(self):
        """Do commit changes"""
        if self.m_editor.GetModify():
            self._object.SaveState()
            self._object.SetText(self.m_editor.GetText())
            if wx.__version__ >= '3.0.0':
                self.m_editor.SetModified(False)
            self.SetBackgroundColour(self._defaulBkColor)
            return True
        else:
            return False

    @property
    def breakpoint(self):
        """return info about if the current line holds breakpoint"""
        return self.m_editor.breakpoint

    def ToggleBreakpoint(self, event):
        """toggle breakpoint"""
        self.m_editor.ToggleBreakpoint(event)

    @property
    def line(self):
        """return current line"""
        return self.m_editor.GetCurrentLine()

    def OnDelete(self, event):
        """Handle delete key"""
        (b, e) = self.m_editor.GetSelection()
        if b == e:
            self.m_editor.CharRight()
        self.m_editor.DeleteBack()

    def OnUpdateSave(self, event):
        """Handles update event"""
        event.Enable(self.m_editor.GetModify())

    def OnSave(self, event):
        """Handles save event"""
        self.Commit()


