"""
This code was taken from https://www.geeksforgeeks.org/make-notepad-using-tkinter/ which was a simple
notepad like editor. I then modified it to make small dialog box.
"""
import textwrap
from tkinter.filedialog import *
from errorHandler import outputError, windows
from globalVariables import epicsCheckWindowPosition
import globalVariables


class PauseForEPICSCheck:

    def __init__(self, pin, comment: str = ''):
        """
        This routine creates a window that will be used when the user should check EPICS displays
        :param pin: The pin/signal whose EPICS display the user should check
        :param comment: The comment from the command line that requested this check. This may provide extra
        instruction as to what should be checked.
        :return:
        """
        self._pin = pin
        self.topWindow = Toplevel()
        # self.topWindow.transient(windows[0].root)
        # self.topWindow.grab_set()  # Make this dialog box modal
        self.topWindow.title('Check EPICS Displays')
        self.topWindow.geometry(f'600x250+{epicsCheckWindowPosition[0]}+{epicsCheckWindowPosition[1]}')
        # set a routine to call if the user  closes the window (by clicking on the 'x')
        self.topWindow.protocol("WM_DELETE_WINDOW", self._closeWindow)
        # make a text area with in the window
        self.textArea = Text(self.topWindow, width=48, height=3,
                             borderwidth=5, relief='sunken', wrap=WORD)

        if pin is not None:  # We were called to check a specific pin/signal
            labelText = f'Please check that EPICS is displaying this bit properly.\n' \
                        f'Bit {pin.signalName} ({pin.PVname}), is {pin.presentValue}.\n'
            if pin.description is not None and pin.description != '':
                labelText += f'\nBit description: {pin.description}\n'
            if comment is not None and comment != '':
                my_wrap = textwrap.TextWrapper(width=90)
                wrap_list = my_wrap.wrap(text=f'Further information: {comment}')
                for line in wrap_list:
                    labelText += line + '\n'
        else:  # We were called with just a comment.
            labelText = ''  # The comment could be long so make it wrap over multiple lines.
            my_wrap = textwrap.TextWrapper(width=90)
            wrap_list = my_wrap.wrap(text=comment)
            for line in wrap_list:
                labelText += line + '\n'

        self._pauseLabel = Label(self.topWindow, text=labelText, justify=LEFT)
        self._btnDisplayOK = Button(self.topWindow, text='Displayed\ncorrectly',
                                    command=self._displayOK, borderwidth=5, relief="raised")
        self._btnDisplayBad = Button(self.topWindow, text='Display\nhas problem',
                                     command=self._displayBad, borderwidth=5, relief="raised")
        self._btnAbort = Button(self.topWindow, text='Abort\nTest', command=self._abortTest,
                                borderwidth=5, relief="raised")

        self._btnDisplayOK.grid(column=0, row=0, sticky=W)
        self._pauseLabel.grid(column=0, row=1, sticky=W)
        self.textArea.grid(column=0, row=2, sticky=N + E + S + W)
        self._btnDisplayBad.grid(column=0, row=3, sticky=W)
        self._btnAbort.grid(column=0, row=3, sticky=E)

        # Fill in the data
        self.textArea.insert('end', 'Enter problem description: ')
        # Select the text, so if user just types, the above text will get deleted.
        self.textArea.tag_add(SEL, '1.0', 'end')

        self.textArea.tag_add('sel', '1.0', 'end')
        self.topWindow.deiconify()
        self.topWindow.lift()  # bring this window to the top
        self.topWindow.attributes('-topmost', True)
        self.topWindow.after_idle(self.topWindow.attributes, '-topmost', False)
        self.topWindow.focus_set()
        self.topWindow.focus_force()
        self.textArea.focus_set()
        windows.append(self.topWindow)  # Save this window so if we abort the test, it can be closed.
        windows[0].root.wait_window(
            self.topWindow)  # Wait until user closes the modal window we opened in above line
        windows.pop()  # Get rid of the pointer to the PauseFor EPICSCheck window

    def _displayOK(self):
        # Called when the user has checked an EPICS display and presses the button that says it is OK.
        # Just close the window.
        self._closeWindow()

    def _displayBad(self):
        # Called when the user has checked an EPICS display and presses the button that says it has problems.
        # Just output and error message and then close the window.
        problemText = self.textArea.get('1.0', END)
        if self._pin is None:  # The error happened on a comment line
            outputError(problemText)
        else:  # The error happened when checking a pin
            outputError(f'Bit: {self._pin.signalName}, has EPICS display problem: {problemText}')
        self._closeWindow()

    def _closeWindow(self):
        """
        This routine is called when the user closes the pause for EPICS check window.
        It just sets the pointer to the window to None to flag it no longer exists and closes the window
        :return:
        """
        # Save the present position of the window to a global variable so we can put the window back up in
        # the same location next time we create it.
        epicsCheckWindowPosition[0] = self.topWindow.winfo_x()
        epicsCheckWindowPosition[1] = self.topWindow.winfo_y()
        self.topWindow.destroy()
        self.topWindow = None

    def _abortTest(self):
        globalVariables.abortTest = True
        self._closeWindow()
