import sys
import numpy as np
import argparse
from PyQt5.QtWidgets import (QApplication, QVBoxLayout, QHBoxLayout, QWidget, QComboBox, QLabel, QSizePolicy, 
                             QGroupBox, QPushButton, QLineEdit, QGridLayout)
from PyQt5.QtCore import Qt, QTimer, QSignalBlocker
from PyQt5.QtGui import QFont, QColor, QPalette
from pydm.widgets.line_edit import PyDMLineEdit
from pydm.widgets.enum_combo_box import PyDMEnumComboBox
from pydm.widgets.label import PyDMLabel
from pydm.widgets.shell_command import PyDMShellCommand
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from epics import caget, caput

ITEMS = ['PMT:LTUH:999', 'PMT:LTUS:999', 'LBLM:LTUH:738:A','LBLM:LTUS:738:A', 'LBLM:LTUH:433:A', 'LBLM:LTUH:105:B']
BEAMS = ['CUH1H: Copper to Hard', 'CUS1H: Copper to Soft', 'SCH1H: SC to Hard', 'SCS1H: SC to Soft', 'SCL1H: SC to Linac', 'SCB1H: SC to BSY Dump', 'SCD1H: SC to Diag0', '1H: Linac']
SCRIPT = {
    'PMT:LTUS:999': 'pydm -m "IOC=SIOC:LTUS:MC04, CPU=CPU:UNDS:SP01, CRATE=CRAT:UNDS:SP01:1,LOCA=LTUS,IOC_UNIT=MC04,INST=0" $TOOLS/pydm/display/evnt/tprDiagSC.ui',
    'LBLM:LTUS:738:A': 'pydm -m "IOC=SIOC:LTUS:MC04, CPU=CPU:UNDS:SP01, CRATE=CRAT:UNDS:SP01:1,LOCA=LTUS,IOC_UNIT=MC04,INST=0" $TOOLS/pydm/display/evnt/tprDiagSC.ui',
    'PMT:LTUH:999': 'pydm -m "IOC=SIOC:LTUH:MC05, CPU=CPU:UNDH:SP01, CRATE=CRAT:UNDH:SP01:1,LOCA=LTUH,IOC_UNIT=MC05,INST=0" $TOOLS/pydm/display/evnt/tprDiagSC.ui',
    'LBLM:LTUH:105:B': 'pydm -m "IOC=SIOC:LTUH:MC04, CPU=CPU:LTUH:SP02, CRATE=CRAT:LTUH:SP02:1,LOCA=LTUH,IOC_UNIT=MC04,INST=0" $TOOLS/pydm/display/evnt/tprDiagSC.ui',
    'LBLM:LTUH:433:A': 'pydm -m "IOC=SIOC:LTUH:MC07, CPU=CPU:LTUH:SP03, CRATE=CRAT:LTUH:SP03:1,LOCA=LTUH,IOC_UNIT=MC07,INST=0" $TOOLS/pydm/display/evnt/tprDiagSC.ui',
    'LBLM:LTUH:738:A': 'pydm -m "IOC=SIOC:LTUH:MC05, CPU=CPU:UNDH:SP01, CRATE=CRAT:UNDH:SP01:1,LOCA=LTUH,IOC_UNIT=MC05,INST=0" $TOOLS/pydm/display/evnt/tprDiagSC.ui',
    }

class MatplotlibWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.head = ''
        self.figure, self.ax1 = plt.subplots(figsize=(10, 6), dpi=90)
        self.ax2 = self.ax1.twinx()
        self.canvas = FigureCanvas(self.figure)
        self.figure.patch.set_facecolor('#F0F0F0')
        self.ax1.set_facecolor('#F0F0F0')
        
        self.xdata, self.ydata1, self.ydata2 = [], [], []
        self.ln1, = self.ax1.plot([], [], 'tab:orange', label='Fast Signal', linewidth=0.75)
        self.ln2, = self.ax2.plot([], [], 'tab:blue', label='Pedestal', linewidth=0.75)
        
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.canvas)
        self.setLayout(layout)
        
        self.init_plot()

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_plot)
        self.timer.start(1000)

    def set_head(self, new_head):
        self.head = new_head
        self.ax1.set_title(new_head)

    def init_plot(self):
        self.ax1.xaxis.set_major_locator(plt.MaxNLocator(10))
        self.ax1.yaxis.set_major_locator(plt.MaxNLocator(15, integer=True))
        self.ax2.yaxis.set_major_locator(plt.MaxNLocator(15, integer=True))

        self.ax1.set_xlabel("Time (Nanoseconds)")
        self.ax1.set_ylabel("Fast Signal (Raw Counts / 2)")
        self.ax2.set_ylabel("Fast Bins")
        
        self.ax1.grid(True, linestyle='--', alpha=0.7)
        self.ax2.grid(True, linestyle=':', alpha=0.7)
        
        self.ax1.set_ylim(15500, 16500)
        self.ax2.set_ylim(-1500, 17000)
        
        lines = self.ln1, self.ln2
        labels = [l.get_label() for l in lines]
        self.ax1.legend(lines, labels, loc='upper right')
        
        self.figure.tight_layout()

    def update_plot(self):
        try:
            self.xdata = caget(f'{self.head}:FAST_WF_TIME')
            self.ydata1 = caget(f'{self.head}:FAST_SIG')
            self.ydata2 = caget(f'{self.head}:SCL_VWF.AVAL')
            
            if self.xdata is None or self.ydata1 is None or self.ydata2 is None:
                raise ValueError("One or more datasets are None")
            
            minlen = min(len(self.xdata), len(self.ydata1), len(self.ydata2))
            self.xdata = self.xdata[:minlen]
            self.ydata1 = self.ydata1[:minlen]
            self.ydata2 = self.ydata2[:minlen]
        except Exception as e:
            print(f"Error retrieving data for {self.head}: {e}")
            self.xdata = np.array([0])
            self.ydata1 = np.array([np.nan])
            self.ydata2 = np.array([np.nan])

        self.ln1.set_data(self.xdata, self.ydata1)
        self.ln2.set_data(self.xdata, self.ydata2)
        
        self.ax1.relim()
        self.ax2.relim()
        self.ax1.autoscale_view()
        self.ax2.autoscale_view()
        
        self.figure.tight_layout()
        self.canvas.draw()

    def resizeEvent(self, event):
        super().resizeEvent(event)
        self.figure.tight_layout()
        self.canvas.draw()

    def set_y_limits(self, axis, ymin=None, ymax=None):
        ax = self.ax1 if axis == 1 else self.ax2
        current_ymin, current_ymax = ax.get_ylim()
        new_ymin = ymin if ymin is not None else current_ymin
        new_ymax = ymax if ymax is not None else current_ymax
        ax.set_ylim(new_ymin, new_ymax)
        self.canvas.draw()

    def auto_scale(self, axis):
        ax = self.ax1 if axis == 1 else self.ax2
        data = self.ydata1 if axis == 1 else self.ydata2
        if len(data) > 0 and not np.isnan(data).all():
            ymin, ymax = np.nanmin(data), np.nanmax(data)
            margin = (ymax - ymin) * 0.1
            ax.set_ylim(ymin - margin, ymax + margin)
        else:
            ax.set_ylim(15500, 16500) if axis == 1 else ax.set_ylim(-1500, 17000)
        self.canvas.draw()

    def get_y_limits(self, axis):
        return self.ax1.get_ylim() if axis == 1 else self.ax2.get_ylim()
    
class PyDMEmbeddedApp(QWidget):
    def __init__(self, parent=None, initial_head='PMT:LTUH:999'):
        super().__init__(parent)
        self.head = initial_head
        self.setAutoFillBackground(True)
        palette = self.palette()
        palette.setColor(QPalette.Window, QColor(240, 240, 240))
        self.setPalette(palette)
        self.init_ui()
        
        if self.head not in ITEMS: self.head = 'PMT:LTUH:999'
        self.dropdown2.setCurrentIndex(ITEMS.index(self.head))
        self.update_head(self.head)

    def init_ui(self):
        self.line_edit1 = PyDMLineEdit()
        self.line_edit2 = PyDMLineEdit()
        self.line_edit3 = PyDMLineEdit()
        self.dropdown1 = PyDMEnumComboBox()
        self.dropdown2 = QComboBox()
        self.dropdown3 = QComboBox()
        self.top_pydm_label = PyDMLabel()
        self.int_value = PyDMLabel()
        self.y1_min, self.y1_max = QLineEdit(), QLineEdit()
        self.y2_min, self.y2_max = QLineEdit(), QLineEdit()
        self.y1_auto = QPushButton("Auto")
        self.y2_auto = QPushButton("Auto")
        self.pwd_button = PyDMShellCommand(command='')
        self.pwd_button.setText("TPR Screen")

        self.dropdown2.addItems(ITEMS)
        self.dropdown3.addItems(BEAMS)
        
        self.dropdown2.currentIndexChanged.connect(self.on_dropdown2_changed)
        self.dropdown3.currentIndexChanged.connect(self.on_dropdown3_changed)
        self.y1_auto.clicked.connect(lambda: self.auto_scale(1))
        self.y2_auto.clicked.connect(lambda: self.auto_scale(2))

        for widget in [self.y1_min, self.y1_max, self.y2_min, self.y2_max]:
            widget.returnPressed.connect(self.update_y_limits)

        self.matplotlib_widget = MatplotlibWidget()

        self.title_label = QLabel(f"{self.head} Fast Channel Diagnostics")
        self.title_label.setAlignment(Qt.AlignCenter)
        self.title_label.setStyleSheet("background-color: rgb(170,170,255); padding: 5px;")
        self.title_label.setFont(QFont("Arial", 14, QFont.Bold))

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.title_label)

        control_layout = QHBoxLayout()

        left_column = QGridLayout()
        left_column.addWidget(QLabel("PMT Select"), 0, 0)
        left_column.addWidget(self.dropdown2, 0, 1)
        left_column.addWidget(QLabel("Ped Width"), 1, 0)
        left_column.addWidget(self.line_edit1, 1, 1)
        left_column.addWidget(QLabel("Gate Start"), 2, 0)
        left_column.addWidget(self.line_edit2, 2, 1)
        left_column.addWidget(QLabel("Gate Width"), 3, 0)
        left_column.addWidget(self.line_edit3, 3, 1)
        left_column.addWidget(QLabel("Enable Scan"), 4, 0)
        left_column.addWidget(self.dropdown1, 4, 1)
        
        left_group = QGroupBox("Controls")
        left_group.setLayout(left_column)
        control_layout.addWidget(left_group, 2)

        middle_column = QGridLayout()
        middle_column.addWidget(QLabel("TPR Panel"), 0, 0)
        middle_column.addWidget(self.pwd_button, 0, 1)
        middle_column.addWidget(QLabel("Beam Select"), 1, 0)
        middle_column.addWidget(self.dropdown3, 1, 1)
        middle_column.addWidget(QLabel("BSSS Data"), 2, 0)
        middle_column.addWidget(self.top_pydm_label, 2, 1)
        middle_column.addWidget(QLabel("Register Data"), 3, 0)
        middle_column.addWidget(self.int_value, 3, 1)
        self.top_pydm_label.setMaximumWidth(150)
        
        
        middle_group = QGroupBox("BSA Scalar and Readbacks")
        middle_group.setLayout(middle_column)
        control_layout.addWidget(middle_group, 1)

        right_column = QGridLayout()
        right_column.addWidget(QLabel("Fast Signal"), 0, 0, 1, 4)
        right_column.addWidget(QLabel("Min:"), 1, 0)
        right_column.addWidget(self.y1_min, 1, 1)
        right_column.addWidget(QLabel("Max:"), 1, 2)
        right_column.addWidget(self.y1_max, 1, 3)
        right_column.addWidget(self.y1_auto, 1, 4)
        right_column.addWidget(QLabel("Pedestal"), 2, 0, 1, 4)
        right_column.addWidget(QLabel("Min:"), 3, 0)
        right_column.addWidget(self.y2_min, 3, 1)
        right_column.addWidget(QLabel("Max:"), 3, 2)
        right_column.addWidget(self.y2_max, 3, 3)
        right_column.addWidget(self.y2_auto, 3, 4)
        
        right_group = QGroupBox("Y-axis Controls")
        right_group.setLayout(right_column)
        control_layout.addWidget(right_group, 1)

        control_widget = QWidget()
        control_widget.setLayout(control_layout)
        control_widget.setFixedHeight(180)

        main_layout.addWidget(control_widget)
        main_layout.addWidget(self.matplotlib_widget, 1)
        self.setLayout(main_layout)

        self.update_y_limit_displays()

    def update_head(self, new_head):
        try:
            self.head = new_head
            self.matplotlib_widget.set_head(new_head)
            self.line_edit1.channel = f"{self.head}:PED_WIDTH"
            self.line_edit2.channel = f"{self.head}:GATE_START"
            self.line_edit3.channel = f"{self.head}:GATE_WIDTH"
            self.dropdown1.channel = f"{self.head}:AutoRearm"
            self.top_pydm_label.channel = f"{self.head}:FAST_POLL"
            self.int_value.channel = f"{self.head}:GATED_INTEGRAL"
            self.title_label.setText(f"{self.head} Fast Channel Diagnostics")
            
            self.setWindowTitle(f"{self.head} Fast Channel Diagnostics")
            if self.head in list(SCRIPT.keys()):
                self.pwd_button.commands = [SCRIPT[self.head]]

            with QSignalBlocker(self.dropdown3):
                default_beam = 'CUH1H' if 'LTUH' in self.head else 'CUS1H'
                for i, pv in enumerate(['CUH1H', 'CUS1H', 'SCH1H', 'SCS1H', 'SCL1H', 'SCB1H', 'SCD1H', '1H']):
                    if pv == default_beam or bool(caget(f'{self.head}:FAST{pv}')):
                        self.dropdown3.setCurrentIndex(i)
                        self.top_pydm_label.channel=f"{self.head}:FAST{pv}"
                        break
                    
            self.update_y_limit_displays()
        except Exception as e:
            print(f"Error updating head to {new_head}: {e}")

    def on_dropdown2_changed(self):
        new_head = self.dropdown2.currentText()
        if caget(f"{new_head}:AutoRearm") is None:
            print(f"PMT not changed to {new_head}")
        else:
            print(f"PMT changed to {new_head}")
            self.update_head(new_head)
            
    def on_dropdown3_changed(self):
        pv_set = " ".join(self.dropdown3.currentText().split(':')[0].split())
        pv_set = f'{self.head}:FAST{pv_set}'
        self.top_pydm_label.channel = pv_set
        caput(pv_set, 1)
        print(f'Beam changed to {pv_set}')

    def update_y_limits(self):
        sender = self.sender()
        if sender in [self.y1_min, self.y1_max]:
            axis = 1
            ymin = float(self.y1_min.text()) if self.y1_min.text() else None
            ymax = float(self.y1_max.text()) if self.y1_max.text() else None
        else:
            axis = 2
            ymin = float(self.y2_min.text()) if self.y2_min.text() else None
            ymax = float(self.y2_max.text()) if self.y2_max.text() else None
        
        self.matplotlib_widget.set_y_limits(axis, ymin, ymax)
        self.update_y_limit_displays()

    def update_y_limit_displays(self):
        y1_min, y1_max = self.matplotlib_widget.get_y_limits(1)
        y2_min, y2_max = self.matplotlib_widget.get_y_limits(2)
        self.y1_min.setText(f"{y1_min:.2f}")
        self.y1_max.setText(f"{y1_max:.2f}")
        self.y2_min.setText(f"{y2_min:.2f}")
        self.y2_max.setText(f"{y2_max:.2f}")

    def auto_scale(self, axis):
        self.matplotlib_widget.auto_scale(axis)
        self.update_y_limit_displays()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Fast Scanner Application")
    parser.add_argument("--pv", type=str, help="Initial PV head")
    args = parser.parse_args()
    app = QApplication(sys.argv)
    
    initial_head = args.pv if args.pv else 'PMT:LTUH:999'
    window = PyDMEmbeddedApp(initial_head=initial_head)
    window.setGeometry(100, 100, 1350, 700)
    window.show()
    sys.exit(app.exec_())