# Author : Nitram Treblig

import wx

import os, time

from lyntin import exported 

from wx import EVT_KEY_DOWN, EVT_CHAR, EVT_CLOSE, EVT_ACTIVATE, EVT_SET_FOCUS

ID_SAVE=100


def restore_command_focus(frame):
    """Restore the main window after the history window has closed."""
    if not frame or getattr(frame, '_closing', False):
        return
    if frame.IsIconized():
        frame.Iconize(False)
    frame.Show(True)
    frame.Raise()
    entry = frame._entry
    # Back in an empty command line, ready for a new command: a message read
    # there (Ctrl+J, Ctrl+Up...) is cleared, and a command being typed is
    # kept in the command history, one Up arrow above.
    try:
        entry.parkDraft()
    except Exception:
        pass
    entry.SetFocus()

class History(wx.Frame):

    # Interval, in milliseconds, between two checks for new view messages.
    REFRESH_MS = 250

    def __init__(self, parent, title, pos, size, text="", view=None):

        # A single application entry in Alt+Tab; history stays above its owner
        # without staying above unrelated applications.
        style = ((wx.DEFAULT_FRAME_STYLE & ~wx.CLOSE_BOX & ~wx.MINIMIZE_BOX)
                 | wx.FRAME_NO_TASKBAR | wx.FRAME_FLOAT_ON_PARENT)

        self._frame = wx.GetTopLevelParent(parent)

        wx.Frame.__init__(self, self._frame, wx.ID_ANY, title, pos, size,style)

        self._frame._history_window = self

        self._parent = parent

        self._text = text

        self._close = False

        self._history_loaded = False

        # Live view: new messages are appended while the window is open,
        # even when the focus is in the text.
        self._view = view

        self._seen = 0

        self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_RICH|wx.TE_AUTO_URL|wx.TE_NOHIDESEL)

        self.control.Bind(EVT_KEY_DOWN, self.onKeyDown)

        self.control.Bind(EVT_SET_FOCUS, self.onSetFocus)

        filemenu = wx.Menu()

        filemenu.Append(ID_SAVE, "&Save"," Save file")

        menuBar = wx.MenuBar()

        menuBar.Append(filemenu,"&File") 

        self.SetMenuBar(menuBar)

        self.Bind(wx.EVT_MENU, self.OnSave, id=ID_SAVE)

        self.sizer = wx.BoxSizer(wx.VERTICAL)

        self.sizer.Add(self.control,1,wx.EXPAND)

        self.SetSizer(self.sizer)

        self.SetAutoLayout(1)

        self.Bind(wx.EVT_CLOSE, self.onExit)

        self.dirname = ''

        self._timer = None

        if view is not None:

          self._timer = wx.Timer(self)

          self.Bind(wx.EVT_TIMER, self.onRefresh, self._timer)

          self._timer.Start(self.REFRESH_MS)



    def onSetFocus(self, event):

      if not self._history_loaded:
        if self._view is not None:
          # Fresh copy at load time, with the count it corresponds to.
          self._text, self._seen = self._view.snapshot()
        self.control.ChangeValue(self._text)
        self.control.SetInsertionPointEnd()
        self.control.ShowPosition(self.control.GetLastPosition())
        self._history_loaded = True
      event.Skip()

    def onRefresh(self, event=None):

      """Appends the new view messages without moving the reading point."""

      if self._close or not self._history_loaded or self._view is None:
        return
      new, self._seen = self._view.getNewMessages(self._seen)
      if not new:
        return
      control = self.control
      start, end = control.GetSelection()
      prefix = "\n" if control.GetLastPosition() > 0 else ""
      # AppendText moves the caret to the end: the reading point and the
      # selection are restored so that the screen reader is not disturbed.
      control.AppendText(prefix + "\n".join(new))
      control.SetSelection(start, end)

    def stopRefresh(self):

      if self._timer is not None:
        self._timer.Stop()
        self._timer = None

    def onKeyDown(self, event):

      keycode = event.GetKeyCode()

      # Tab or Escape: back to the command entry.
      if (keycode in (wx.WXK_TAB, wx.WXK_ESCAPE)
          and not event.ControlDown() and not event.AltDown()):
        if not self._close:
          self._close = True
          self._parent.Enable(True)
          self.Close(True)
          wx.CallAfter(restore_command_focus, self._frame)
        return  # Consume Tab so Windows cannot apply it to another window.
      event.Skip()

    def onExit(self, event):

      if not self._close:

        event.Veto()

        return

      if getattr(self, '_timer', None) is not None:
        self.stopRefresh()
      if getattr(self._frame, '_history_window', None) is self:
        self._frame._history_window = None
      if not getattr(self._frame, '_closing', False):
        self._parent.Enable(True)
      self.Destroy()

        

    def OnSave(self,event):

        dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*",\

                wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)

        if dlg.ShowModal() == wx.ID_OK:

            itcontains = self.control.GetValue()



            self.filename=dlg.GetFilename()

            self.dirname=dlg.GetDirectory()

            filehandle=open(os.path.join(self.dirname, self.filename),'w', encoding="utf-8")

            filehandle.write(itcontains)

            filehandle.close()

        dlg.Destroy()




