import os
import json
import sys
import re
import glob
from pydm import Display
from qtpy.QtWidgets import QApplication, QFontComboBox, QVBoxLayout, QTextEdit, QWidget, QStyle
from qtpy.QtGui import QSyntaxHighlighter, QTextCharFormat, QColor, QFont
from qtpy.QtCore import QRegularExpression, Qt, QTimer

MAXLEN = 10000

def list_ioc(self) -> dict:
    """Retrieves and returns a sorted dictionary of motion IOCs with their details"""
    os.system('iocConsole -ls > ioc_python_get_console.txt')
    
    motion = []
    with open('ioc_python_get_console.txt', 'r') as file:
        for line in file:
            try:
                ioc = f"{{{line.split('{')[1].split('}')[0]}}}"
                ioc = json.loads(ioc.replace("'",'"'))
                if 'ioc' in ioc['name'] and os.path.exists(os.path.expandvars(f'$IOC_DATA/{ioc["name"]}/screenlog.0')):
                    if ('mc' in ioc['name'].split('-')[-1]) and (ioc['name'].split('-')[1] == self.init_to_set.split('-')[1]):
                        motion.append(ioc['name'])
            except:
                pass
    
    os.system('rm -rf ioc_python_get_console.txt')
    return sorted(motion)

def retrieve_console(self) -> None:
    """Retrieves console output from IOC screenlog file, cleans it, and updates text displays"""
    filepath = os.path.expandvars(f'$IOC_DATA/{self.DropdownIOC.currentText()}/{self.DropdownScreenlog.currentText()}')
    if not os.path.exists(filepath):
        self._show_error()
        return

    os.system(f'tail -n {MAXLEN} {filepath} > ioc_python_console_copy.txt')
    try:
        with open('ioc_python_console_copy.txt', 'r', encoding='latin-1', errors='ignore') as file:
            output = file.read()
            
            cleanup_patterns = [
                r'\x08|\x07|\x1b\[[0-9;]*[a-zA-Z]',
                r'\^\[K', r'', r'', r'\^\[C', r'\^\[P',
                r'\^\[28@', r'\^\[31P', r'\^\[7PepicsEnvSet',
                r'\^\[10P#', r'\^\[14P#', r'\^\[32P',
                r'\^\[2Pfile', r'\^\[[0-9]+P'
            ]
            
            cleaned_output = output
            for pattern in cleanup_patterns:
                replaced_text = ''
                if pattern.endswith('epicsEnvSet') or pattern.endswith('#') or pattern.endswith('file'):
                    replaced_text = pattern.split('P')[1]
                cleaned_output = re.sub(pattern, replaced_text, cleaned_output)
            
            self.FilteredText.setPlainText(cleaned_output)
            
            for text_edit in [self.FilteredText]:
                text_edit.verticalScrollBar().setValue(text_edit.verticalScrollBar().maximum())
    finally:
        os.system('rm -rf ioc_python_console_copy.txt')

class ConsoleHighlighter(QSyntaxHighlighter):
    """Syntax highlighter for the console output with rules for comments, warnings, paths, etc."""
    def __init__(self, parent=None):
        super(ConsoleHighlighter, self).__init__(parent)
        
        self.highlighting_rules = [
            (QRegularExpression(r"#.*"), self._create_format(QColor("green"))),
            (QRegularExpression(r"\b(warning|error|failed|fail|fault|faulted)\b", QRegularExpression.CaseInsensitiveOption), 
             self._create_format(QColor("red"))),
            (QRegularExpression(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"), self._create_format(QColor("purple"))),
            (QRegularExpression(r"\b[A-Za-z0-9_]+(?=\()"), self._create_format(QColor("blue"))),
            (QRegularExpression(r"(?<![#])((?:\$\{[A-Za-z0-9_]+\}|\$\([A-Za-z0-9_]+\)|\$[A-Za-z0-9_]+|/)[A-Za-z0-9_\./\-]*(?:/|\$\{[A-Za-z0-9_]+\}|\$\([A-Za-z0-9_]+\)|\$[A-Za-z0-9_]+)(?:[A-Za-z0-9_\./\-]+|\$\{[A-Za-z0-9_]+\}|\$\([A-Za-z0-9_]+\)|\$[A-Za-z0-9_]+)*)+"), 
             self._create_format(QColor("magenta"))),
            (QRegularExpression(r"(?<![/#])[A-Za-z][A-Za-z0-9_]*(?:/[A-Za-z0-9_\.\-]+)+"), 
             self._create_format(QColor("magenta")))
        ]

    def _create_format(self, color):
        """Creates and returns a text format with the specified color"""
        format = QTextCharFormat()
        format.setForeground(color)
        return format

    def highlightBlock(self, text):
        """Applies syntax highlighting to the given text block"""
        if "time-stamp" in text:
            for pattern, format in self.highlighting_rules[:4]:
                it = pattern.globalMatch(text)
                while it.hasNext():
                    match = it.next()
                    self.setFormat(match.capturedStart(), match.capturedLength(), format)
            return
            
        comment_match = QRegularExpression(r"^\s*#").match(text)
        if comment_match.hasMatch():
            self.setFormat(0, len(text), self.highlighting_rules[0][1])
            return
            
        for pattern, format in self.highlighting_rules:
            it = pattern.globalMatch(text)
            while it.hasNext():
                match = it.next()
                start_pos = match.capturedStart()
                matched_text = match.captured()
                
                comment_start = text.find("#")
                if comment_start == -1 or start_pos < comment_start:
                    if "/" in pattern.pattern() and all(part.isdigit() for part in matched_text.split("/") if part):
                        continue
                    self.setFormat(start_pos, match.capturedLength(), format)

class MyDisplay(Display):
    """Main display class for the IOC console viewer application"""
    def __init__(self, parent=None, args=None, macros=None):
        super(MyDisplay, self).__init__(parent=parent, args=args, macros=macros)
        
        try:
            macro_ioc_raw = macros.get('ioc')
        except:
            macro_ioc_raw = "sioc-undh-mc12"
            
        self.init_to_set = macro_ioc_raw.lower().replace(':','-')
        ioc_list = list_ioc(self)
        self.DropdownIOC.addItems(['Select IOC'] + ioc_list)
        self.Fetch.clicked.connect(self.fetch_command)
        self.SearchBar.textChanged.connect(self.search_command)
        self.SearchUp.clicked.connect(self.search_up_command)
        self.SearchDown.clicked.connect(self.search_down_command)
        
        if macro_ioc_raw.lower().replace(':','-') in ioc_list:
            self.DropdownIOC.setCurrentText(self.init_to_set)

        self.current_ioc = "None"
        self.font_combo = QFontComboBox()
        self.font_combo.setCurrentFont(QFont("Courier New"))
        self.font_combo.currentFontChanged.connect(self.change_font)
        
        layout = self.findChild(QVBoxLayout)
        if layout:
            layout.insertWidget(0, self.font_combo)
        
        for text_edit in [self.FilteredText]:
            text_edit.setLineWrapMode(QTextEdit.NoWrap)
            text_edit.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        
        self.change_font(self.font_combo.currentFont())
        self.FilteredText = self.findChild(QTextEdit, "FilteredText")
        self.highlighter = ConsoleHighlighter(self.FilteredText.document())
        self.DropdownIOC.currentIndexChanged.connect(self.fetch_command)
        self.DropdownScreenlog.currentIndexChanged.connect(self.fetch_command)
        
        QTimer.singleShot(20, self.fetch_command)
        
    def search_command(self):
        """Search for text in the console output and highlight matches"""
        search_text = self.SearchBar.text()
        if not search_text:
            self.FilteredText.setExtraSelections([])
            self.SearchFound.setText("0 / 0")
            return
        document = self.FilteredText.document()
        cursor = document.find(search_text)
        
        selections = []
        self.search_positions = []
        current_pos = 0

        while not cursor.isNull():
            selection = QTextEdit.ExtraSelection()
            selection.format.setBackground(QColor("yellow"))
            selection.format.setForeground(QColor("black"))
            selection.cursor = cursor
            selections.append(selection)
            
            self.search_positions.append(cursor.position())
            
            current_pos = cursor.position() + cursor.selectedText().__len__()
            cursor = document.find(search_text, current_pos)
        
        self.FilteredText.setExtraSelections(selections)
        self.current_search_index = 0 if self.search_positions else -1
        
        total_matches = len(self.search_positions)
        current_match = self.current_search_index + 1 if self.current_search_index >= 0 else 0
        self.SearchFound.setText(f"{current_match} / {total_matches}")

        if self.search_positions:
            cursor = self.FilteredText.textCursor()
            cursor.setPosition(self.search_positions[0])
            self.FilteredText.setTextCursor(cursor)
            self.FilteredText.ensureCursorVisible()

    def search_up_command(self):
        """Navigate to the previous search result"""
        if not hasattr(self, 'search_positions') or not self.search_positions:
            return

        if self.current_search_index > 0:
            self.current_search_index -= 1
        else:
            self.current_search_index = len(self.search_positions) - 1
        
        cursor = self.FilteredText.textCursor()
        cursor.setPosition(self.search_positions[self.current_search_index])
        self.FilteredText.setTextCursor(cursor)
        self.FilteredText.ensureCursorVisible()
        
        current_match = self.current_search_index + 1
        total_matches = len(self.search_positions)
        self.SearchFound.setText(f"{current_match} / {total_matches}")

    def search_down_command(self):
        """Navigate to the next search result"""
        if not hasattr(self, 'search_positions') or not self.search_positions:
            return

        if self.current_search_index < len(self.search_positions) - 1:
            self.current_search_index += 1
        else:
            self.current_search_index = 0
        
        cursor = self.FilteredText.textCursor()
        cursor.setPosition(self.search_positions[self.current_search_index])
        self.FilteredText.setTextCursor(cursor)
        self.FilteredText.ensureCursorVisible()
        
        current_match = self.current_search_index + 1
        total_matches = len(self.search_positions)
        self.SearchFound.setText(f"{current_match} / {total_matches}")
        
    def change_font(self, font):
        """Updates the font for text displays"""
        font.setPointSize(10)
        self.FilteredText.setFont(font)
        
    def fetch_command(self):
        """Fetches the console output when requested"""
        self.SearchBar.setText("")
        self.SearchFound.setText("")
        self.Title.setText(self.DropdownIOC.currentText())
        if self.current_ioc != self.DropdownIOC.currentText():
            items = sorted(glob.glob(os.path.expandvars(f'$IOC_DATA/{self.DropdownIOC.currentText()}/screenlog*')))
            for i in range(len(items)):
                items[i] = items[i].split('/')[-1]
            self.DropdownScreenlog.blockSignals(True)
            self.DropdownScreenlog.clear()
            self.DropdownScreenlog.addItems(['Select Screenlog'] + items)
            self.DropdownScreenlog.setCurrentText('screenlog.0')
        self.DropdownScreenlog.blockSignals(False)
        self.current_ioc = self.DropdownIOC.currentText()
        if self.DropdownIOC.currentText() != 'Select IOC':
            try:
                self.ShellReboot.commands = [f'iocConsole --cleanup {self.DropdownIOC.currentText()} && sleep 2 && iocConsole --stayup {self.DropdownIOC.currentText()}']
                for widget in self.findChildren(QWidget):
                    if "PYDM_" in widget.objectName() and hasattr(widget, "channel"):
                        widget.channel = f"{self.DropdownIOC.currentText().upper().replace('-',':')}:{widget.objectName().split('PYDM_')[1]}"
            
                retrieve_console(self)
            except:
                self._show_error()
        else:
            self.DropdownScreenlog.setCurrentText('Select Screenlog')
            self._show_error()
            
        self.DropdownIOC.setMaxVisibleItems(5)
    
    def _show_error(self):
        """Displays error message when screenlog cannot be retrieved"""
        error_msg = 'There is no screenlog'
        self.FilteredText.setText(error_msg)
        
    def ui_filename(self):
        """Returns the UI filename"""
        return os.path.expandvars('$PYDM/mc/Common/ViewIOC.ui')

    def ui_filepath(self):
        """Returns the full UI filepath"""
        return os.path.join(os.path.dirname(os.path.realpath(__file__)), self.ui_filename())

if __name__ == '__main__':

    app = QApplication(sys.argv)
    widget = MyDisplay()
    widget.show()
    sys.exit(app.exec_())
