import sys
import os
import subprocess
from pydm import Display, PyDMApplication

from PyQt5.QtWidgets import QMainWindow, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget, QGridLayout, QPushButton, QMessageBox, QStyle
from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtGui import QColor

class TreeDiagram(Display):
    def __init__(self, parent=None, args=None, macros=None):
        super(TreeDiagram, self).__init__(parent=parent, args=args, macros=macros)

        # Main layout
        main_layout = QVBoxLayout()

        # Button layout
        button_layout = QGridLayout()
        button_layout.setSpacing(5)

        # Get the PYDM environment variable
        pydm_path = os.environ.get("PYDM")
        if pydm_path is None:
            QMessageBox.warning(self, "Warning", "PYDM environment variable not set.")
            pydm_path = ""

        # Expand All button
        self.expand_all_btn = QPushButton("Expand All", self)
        self.expand_all_btn.setIcon(self.style().standardIcon(QStyle.SP_TitleBarUnshadeButton))
        self.expand_all_btn.clicked.connect(self.expand_all)
        button_layout.addWidget(self.expand_all_btn, 0, 0)

        # Close All button
        self.close_all_btn = QPushButton("Close All", self)
        self.close_all_btn.setIcon(self.style().standardIcon(QStyle.SP_TitleBarShadeButton))
        self.close_all_btn.clicked.connect(self.close_all)
        button_layout.addWidget(self.close_all_btn, 0, 1)

        # IOC Button
        self.ioc_btn = QPushButton("Expand IOC", self)
        self.ioc_btn.setIcon(self.style().standardIcon(QStyle.SP_MediaSeekForward))
        self.ioc_btn.clicked.connect(self.expand_ioc)
        button_layout.addWidget(self.ioc_btn, 0, 2)
        
        # IOC Manager button
        ioc_manager_ui_file = os.path.join(pydm_path, "misc", "ioc_stats_vioc.ui")
        ioc_manager_ui_file = os.path.expandvars(ioc_manager_ui_file)
        self.ioc_manager_btn = QPushButton("IOC Manager")
        self.ioc_manager_btn.setIcon(self.style().standardIcon(QStyle.SP_TitleBarNormalButton))
        self.ioc_manager_btn.clicked.connect(
            lambda: self.open_related_display(ioc_manager_ui_file, self.ioc_manager_btn.macros)
        )
        button_layout.addWidget(self.ioc_manager_btn, 1, 0)

        # ASYN Manager button
        asyn_manager_ui_file = os.path.join(pydm_path, "misc", "asyn_octet.ui")
        asyn_manager_ui_file = os.path.expandvars(asyn_manager_ui_file)
        self.asyn_manager_btn = QPushButton("ASYN Manager")
        self.asyn_manager_btn.setIcon(self.style().standardIcon(QStyle.SP_TitleBarNormalButton))
        self.asyn_manager_btn.clicked.connect(
            lambda: self.open_related_display(asyn_manager_ui_file, self.asyn_manager_btn.macros)
        )
        button_layout.addWidget(self.asyn_manager_btn, 1, 1)
        
        # Motor Expert Button
        motor_expert_ui_file = os.path.join(pydm_path, 'mc', 'mc_expert_motor_controls.py')
        motor_expert_ui_file = os.path.expandvars(motor_expert_ui_file)
        self.motor_expert_button = QPushButton("Motor Expert")
        self.motor_expert_button.setIcon(self.style().standardIcon(QStyle.SP_TitleBarNormalButton))
        self.motor_expert_button.clicked.connect(
            lambda: self.open_related_display(motor_expert_ui_file, self.motor_expert_button.macros)
        )
        button_layout.addWidget(self.motor_expert_button, 1, 2)

        # Add button layout to main layout
        main_layout.addLayout(button_layout)

        # Tree widget
        self.tree = QTreeWidget(self)
        self.tree.setHeaderLabels(["Hierarchy", "Variable", "Device"])
        self.tree.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        main_layout.addWidget(self.tree)

        # Set the main layout
        self.setLayout(main_layout)
        self.set_window_size()

        self.create_tree()
        self.setup_button_connections()
        
    def set_window_size(self):
        # Find the top-level window
        top_window = self
        while top_window.parent():
            top_window = top_window.parent()
        
        # Set the window size
        top_window.setGeometry(100, 100, 800, 800)  # Adjust these values as needed

    def open_related_display(self, filename, macros):
        """Opens a related display using subprocess.Popen."""
        if not os.path.isfile(filename):
            QMessageBox.warning(
                self, "Warning", f"File does not exist:\n{filename}"
            )
            return

        command = ["pydm"]
        if macros:
            # Properly format the macros for the command line
            macro_args = []
            for key, value in macros.items():
                macro_args.append(f"{key}={value}")
            command.extend(["-m", ",".join(macro_args), filename])

        subprocess.Popen(command)

    def setup_button_connections(self):
        self.tree.itemSelectionChanged.connect(self.update_button_macros)
        self.asyn_manager_btn.setDisabled(True)
        self.asyn_manager_btn.setVisible(False)
        self.ioc_manager_btn.setDisabled(True)
        self.ioc_manager_btn.setVisible(False)
        self.motor_expert_button.setDisabled(True)
        self.motor_expert_button.setVisible(False)

    @pyqtSlot()
    def update_button_macros(self):
        selected_items = self.tree.selectedItems()
        if selected_items:
            selected_item = selected_items[0]

            # Traverse to the top-level item (Station)
            top_level_item = selected_item
            while top_level_item.parent():
                top_level_item = top_level_item.parent()

            # Find the IOC (second level) - traverse down from the top
            ioc_item = None
            for i in range(top_level_item.childCount()):
                child = top_level_item.child(i)
                if selected_item == child or self.is_ancestor(selected_item, child):
                    ioc_item = child
                    break

            # Find the MOC/CPU (third level) - traverse down from the IOC
            moc_item = None
            if ioc_item:
                for i in range(ioc_item.childCount()):
                    child = ioc_item.child(i)
                    if selected_item == child or self.is_ancestor(selected_item, child):
                        moc_item = child
                        break
                    
            # Find the Motor (fourth level) - traverse down from the MOC
            motor_item = None
            if moc_item:
                for i in range(moc_item.childCount()):
                    child = moc_item.child(i)
                    if selected_item == child or self.is_ancestor(selected_item, child):
                        motor_item = child              
                        break

            # Update macros for IOC Manager button
            self.ioc_manager_btn.macros = {"ioc": ioc_item.text(0)} if ioc_item else None
            self.asyn_manager_btn.macros = {"P": moc_item.text(0), "R": ":ASYN"} if moc_item else None
            self.motor_expert_button.macros = {"P": motor_item.text(1), "M": ':' + motor_item.text(2) + ':MOTR'} if motor_item else None
            
        else:
            self.ioc_manager_btn.macros = None
            self.asyn_manager_btn.macros = None
            self.motor_expert_button.macros = None
            
        if self.ioc_manager_btn.macros is None:
            self.ioc_manager_btn.setDisabled(True)
            self.ioc_manager_btn.setVisible(False)
        else:
            self.ioc_manager_btn.setEnabled(True)
            self.ioc_manager_btn.setVisible(True)
            
        if self.asyn_manager_btn.macros is None:
            self.asyn_manager_btn.setDisabled(True)
            self.asyn_manager_btn.setVisible(False)
        else:
            self.asyn_manager_btn.setEnabled(True)
            self.asyn_manager_btn.setVisible(True)
            
        if self.motor_expert_button.macros is None:
            self.motor_expert_button.setDisabled(True)
            self.motor_expert_button.setVisible(False)
        else:
            self.motor_expert_button.setEnabled(True)
            self.motor_expert_button.setVisible(True)

    def is_ancestor(self, item, ancestor):
        """Checks if ancestor is an ancestor of item."""
        parent = item.parent()
        while parent:
            if parent == ancestor:
                return True
            parent = parent.parent()
        return False

    def create_tree(self):
        data = [
            # Station A data
            ("Station A", "SIOC:UNDH:MC15", "CPU:UNDH:MC02", "C1 X", "PowerMAC", "MIRR:UNDH:2141", "X"),
            ("Station A", "SIOC:UNDH:MC15", "CPU:UNDH:MC02", "C1 Z", "PowerMAC", "MIRR:UNDH:2141", "Z"),
            ("Station A", "SIOC:UNDH:MC15", "CPU:UNDH:MC02", "C1 Roll C", "PowerMAC", "MIRR:UNDH:2141", "ROLL_C"),
            ("Station A", "SIOC:UNDH:MC15", "CPU:UNDH:MC02", "C1 Roll F", "PowerMAC", "MIRR:UNDH:2141", "ROLL_F"),
            ("Station A", "SIOC:UNDH:MC15", "CPU:UNDH:MC02", "C1 Pitch C", "PowerMAC", "MIRR:UNDH:2141", "PITCH_C"),
            ("Station A", "SIOC:UNDH:MC15", "CPU:UNDH:MC02", "C1 Pitch F", "PowerMAC", "MIRR:UNDH:2141", "PITCH_F"),
            ("Station A", "SIOC:UNDH:MC15", "MOC:UNDH:MC14", "X11 X", "SmarAct", "PROF:UNDH:2140", "X"),
            ("Station A", "SIOC:UNDH:MC15", "MOC:UNDH:MC14", "X11 Y", "SmarAct", "PROF:UNDH:2140", "Y"),
            ("Station A", "SIOC:UNDH:MC15", "MOC:UNDH:MC15", "C1 Y", "SmarAct", "MIRR:UNDH:2141", "Y"),
            ("Station A", "SIOC:UNDH:MC15", "MOC:UNDH:MC15", "C1 Ds", "SmarAct", "MIRR:UNDH:2141", "DS"),
            ("Station A", "SIOC:UNDH:MC15", "MOC:UNDH:MC15", "C1 Dp", "SmarAct", "MIRR:UNDH:2141", "DP"),
            ("Station A", "SIOC:UNDH:MC15", "MOC:UNDH:MC25", "X11 Focus", "NewFocus", "CAMR:UNDH:2140", "IRIS"),
            ("Station A", "SIOC:UNDH:MC15", "MOC:UNDH:MC25", "M1 Focus", "NewFocus", "CAMR:UNDH:2141", "FOCUS"),
            ("Station A", "SIOC:UNDH:MC15", "MOC:UNDH:MC26", "M2 Focus", "NewFocus", "INST:UNRH:300", "FOCUS"),
            ("Station A", "SIOC:UNDH:MC15", "MOC:UNDH:MC26", "D2 X", "NewFocus", "INST:UNRH:300", "X"),
            ("Station A", "SIOC:UNDH:MC15", "MOC:UNDH:MC26", "D2 Y", "NewFocus", "INST:UNRH:300", "Y"),
            ("Station A", "SIOC:UNDH:MC16", "CPU:UNDH:MC03", "C2 X", "PowerMAC", "MIRR:UNRH:300", "X"),
            ("Station A", "SIOC:UNDH:MC16", "CPU:UNDH:MC03", "C2 Z", "PowerMAC", "MIRR:UNRH:300", "Z"),
            ("Station A", "SIOC:UNDH:MC16", "CPU:UNDH:MC03", "C2 Roll C", "PowerMAC", "MIRR:UNRH:300", "ROLL_C"),
            ("Station A", "SIOC:UNDH:MC16", "CPU:UNDH:MC03", "C2 Roll F", "PowerMAC", "MIRR:UNRH:300", "ROLL_F"),
            ("Station A", "SIOC:UNDH:MC16", "CPU:UNDH:MC03", "C2 Pitch C", "PowerMAC", "MIRR:UNRH:300", "PITCH_C"),
            ("Station A", "SIOC:UNDH:MC16", "CPU:UNDH:MC03", "C2 Pitch F", "PowerMAC", "MIRR:UNRH:300", "PITCH_F"),
            ("Station A", "SIOC:UNDH:MC16", "MOC:UNDH:MC16", "C2 Y", "SmarAct", "MIRR:UNRH:300", "Y"),
            ("Station A", "SIOC:UNDH:MC16", "MOC:UNDH:MC16", "C2 Ds", "SmarAct", "MIRR:UNRH:300", "DS"),
            ("Station A", "SIOC:UNDH:MC16", "MOC:UNDH:MC16", "C2 Dp", "SmarAct", "MIRR:UNRH:300", "DP"),
            ("Station A", "SIOC:UNDH:MC16", "MOC:UNDH:MC17", "X21 Y", "SmarAct", "PROF:UNRH:285", "Y"),
            ("Station A", "SIOC:UNDH:MC16", "MOC:UNDH:MC18", "CRL1 X", "SmarAct", "LENS:UNRH:200", "X"),
            ("Station A", "SIOC:UNDH:MC16", "MOC:UNDH:MC18", "CRL1 Y", "SmarAct", "LENS:UNRH:200", "Y"),

            # Station B data
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC27", "M3 Focus", "NewFocus", "CAMR:UNRH:700", "FOCUS"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC28", "M4 Focus", "NewFocus", "CAMR:UNDH:1350", "FOCUS"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC04", "C3 X", "PowerMAC", "MIRR:UNDH:1350", "X"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC04", "C3 Z", "PowerMAC", "MIRR:UNDH:1350", "Z"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC04", "C3 Roll C", "PowerMAC", "MIRR:UNDH:1350", "ROLL_C"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC04", "C3 Roll F", "PowerMAC", "MIRR:UNDH:1350", "ROLL_F"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC04", "C3 Pitch C", "PowerMAC", "MIRR:UNDH:1350", "PITCH_C"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC04", "C3 Pitch F", "PowerMAC", "MIRR:UNDH:1350", "PITCH_F"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC05", "C4 X", "PowerMAC", "MIRR:UNRH:700", "X"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC05", "C4 Z", "PowerMAC", "MIRR:UNRH:700", "Z"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC05", "C4 Roll C", "PowerMAC", "MIRR:UNRH:700", "ROLL_C"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC05", "C4 Roll F", "PowerMAC", "MIRR:UNRH:700", "ROLL_F"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC05", "C4 Pitch C", "PowerMAC", "MIRR:UNRH:700", "PITCH_C"),
            ("Station B", "SIOC:UNDH:MC15", "CPU:UNDH:MC05", "C4 Pitch F", "PowerMAC", "MIRR:UNRH:700", "PITCH_F"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC20", "C3 Y", "SmarAct", "MIRR:UNDH:1350", "Y"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC20", "C3 Ds", "SmarAct", "MIRR:UNDH:1350", "DS"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC20", "C3 Dp", "SmarAct", "MIRR:UNDH:1350", "DP"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC22", "C4 Y", "SmarAct", "MIRR:UNRH:700", "Y"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC22", "C4 Ds", "SmarAct", "MIRR:UNRH:700", "DS"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC22", "C4 Dp", "SmarAct", "MIRR:UNRH:700", "DP"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC19", "X31 X", "SmarAct", "MPROF:UNRH:699", "X"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC19", "X31 Y", "SmarAct", "PROF:UNRH:699", "Y"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC23", "X41 X", "SmarAct", "MPROF:UNRH:885", "X"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC23", "X41 Y", "SmarAct", "PROF:UNRH:885", "Y"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC24", "X42 X", "SmarAct", "PROF:UNDH:1353", "X"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC24", "X42 Y", "SmarAct", "PROF:UNDH:1353", "Y"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC21", "CRL2 X", "SmarAct", "LENS:UNRH:800", "X"),
            ("Station B", "SIOC:UNDH:MC15", "MOC:UNDH:MC21", "CRL2 Y", "SmarAct", "LENS:UNRH:800", "Y"),

            # Station C data
            ("Station C", "SIOC:UNDH:MC15", "Unknown", "X23 X", "SmarAct", "PROF:UNRH:325", "X"),
            ("Station C", "SIOC:UNDH:MC15", "Unknown", "X23 Y", "SmarAct", "PROF:UNRH:325", "Y"),
            ("Station C", "SIOC:UNDH:MC15", "Unknown", "X23G X", "SmarAct", "GRAT:UNRH:325", "X"),
            ("Station C", "SIOC:UNDH:MC15", "Unknown", "X23G Y", "SmarAct", "GRAT:UNRH:325", "Y"),
            ("Station C", "SIOC:UNDH:MC15", "Unknown", "X23E X", "SmarAct", "INST:UNRH:325", "X"),
            ("Station C", "SIOC:UNDH:MC15", "Unknown", "X23E Y", "SmarAct", "INST:UNRH:325", "Y"),

            # Station D data
            ("Station D", "SIOC:UNDH:MC13", "MOC:UNDH:MC12", "X24 X", "SmarAct", "PROF:UNRH:500", "X"),
            ("Station D", "SIOC:UNDH:MC13", "MOC:UNDH:MC12", "X24 Y", "SmarAct", "PROF:UNRH:500", "Y"),
            ("Station D", "SIOC:UNDH:MC13", "MOC:UNDH:MC12", "M5 Focus", "NewFocus", "CAMR:UNRH:500", "FOCUS"),

            # Station E data
            ("Station E", "SIOC:UNDH:MC12", "CPU:UNDH:MC01", "Camera X", "PMAC", "MOVR:UNRH:E735", "X"),
            ("Station E", "SIOC:UNDH:MC12", "CPU:UNDH:MC01", "Camera Y", "PMAC", "MOVR:UNRH:E735", "Y"),
            ("Station E", "SIOC:UNDH:MC12", "CPU:UNDH:MC01", "Camera Z", "PMAC", "MOVR:UNRH:E735", "Z"),
            ("Station E", "SIOC:UNDH:MC12", "CPU:UNDH:MC01", "Wavefront X", "PMAC", "MOVR:UNRH:E730", "X"),
            ("Station E", "SIOC:UNDH:MC12", "CPU:UNDH:MC01", "Wavefront Y", "PMAC", "MOVR:UNRH:E730", "Y"),
            ("Station E", "SIOC:UNDH:MC12", "CPU:UNDH:MC01", "Wavefront Z", "PMAC", "MOVR:UNRH:E730", "Z"),

            # Station F data
            ("Station F", "SIOC:UNDH:MC12", "CPU:UNDH:MC01", "Camera", "PMAC", "BOD:UNDH:1369", "X"),
            ("Station F", "SIOC:UNDH:MC12", "CPU:UNDH:MC01", "BOD Paddle", "PMAC", "BOD:UNDH:1369", "Y"),
        ]

        # Create the tree structure
        tree_structure = {}
        for item in data:
            station, ioc, moc, name, controller, variable, device = item
            if station not in tree_structure:
                tree_structure[station] = {}
            if ioc not in tree_structure[station]:
                tree_structure[station][ioc] = {}
            if moc not in tree_structure[station][ioc]:
                tree_structure[station][ioc][moc] = {}
            if name not in tree_structure[station][ioc][moc]:
                tree_structure[station][ioc][moc][name] = (controller, variable, device)

        # Populate the tree widget
        for station, iocs in tree_structure.items():
            station_item = QTreeWidgetItem(self.tree, [station])
            station_item.setForeground(0, QColor('#8C1515'))
            for ioc, mocs in iocs.items():
                ioc_item = QTreeWidgetItem(station_item, [ioc])
                # Set font color to the background color to make it invisible
                ioc_item.setForeground(0, ioc_item.background(0))
                for moc, names in mocs.items():
                    moc_item = QTreeWidgetItem(ioc_item, [moc])
                    # Set font color to the background color to make it invisible
                    moc_item.setForeground(0, moc_item.background(0))
                    for name, details in names.items():
                        controller, variable, device = details
                        name_item = QTreeWidgetItem(moc_item, [name])
                        # name_item.setText(1, controller)  # Controller in the second column
                        name_item.setText(1, variable)  # Variable in the third column
                        name_item.setText(2, device)  # Device in the fourth column

        # Adjust column widths
        for i in range(self.tree.columnCount()):
            self.tree.resizeColumnToContents(i)

        # Make the first column wider
        first_column_width = self.tree.columnWidth(0)
        self.tree.setColumnWidth(0, first_column_width * 3)

        # Increase font size by 1
        font = self.tree.font()
        font.setPointSize(font.pointSize() + 1)
        self.tree.setFont(font)

        # Ensure minimum width for each column (except the first one)
        min_width = 150
        for i in range(1, self.tree.columnCount()):
            if self.tree.columnWidth(i) < min_width:
                self.tree.setColumnWidth(i, min_width)

    def get_column_value(self, item, column_index):
        # This function is no longer directly used but kept for potential future use.
        while item:
            value = item.text(column_index)
            if value:
                return value
            item = item.parent()
        return None

    def expand_all(self):
        self.tree.expandAll()
        
    def expand_ioc(self):
        self.tree.expandToDepth(0)

    def close_all(self):
        self.tree.collapseAll()

if __name__ == "__main__":
    app = PyDMApplication(use_main_window=False)
    window = QMainWindow()
    tree_diagram = TreeDiagram(window)
    window.setCentralWidget(tree_diagram)
    window.setGeometry(100, 100, 800, 800)
    window.setWindowTitle("CBXFEL Hierarchy Tree")
    window.show()
    sys.exit(app.exec_())