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

import wx
import tran
from app.ui.pane import BasePane
from activity.files.ui import ui as ui


# Implementing TextPane
class TextPane(BasePane, ui.TextPane):
    """Implements text editor"""

    def __init__(self, parent, mainframe, fileobj):
        """Intialization of text editor"""
        self._parent = parent
        self._mainframe = mainframe
        self._object = fileobj
        super(TextPane, self).__init__(parent)
        self._defaulBkColor = self.GetBackgroundColour()
        self.m_editor.SetText(fileobj.GetText())
        self.m_editor.HandleBookmarks(fileobj.bookmarks)
        self.m_editor.EnableBookmarks(True)
        self.m_editor.Initialize()
        self.m_editor.SetReadOnly(fileobj._readOnly)
        self.Layout()

    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)

    @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())
            self.m_editor.SetModified(False)
            self.SetBackgroundColour(self._defaulBkColor)
            return True
        else:
            return False

    @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()


