import pyqtgraph as pg
from pyqtgraph import Qt
from pyqtgraph.Qt import QtCore, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

from .DataExtractorLyse import DataExtractorManager


class DataPlot(QSplitter):
    def __init__(self, title, **kwargs):
        super().__init__(**kwargs)

        # Orientation of plot and title (and other information)
        self.setOrientation(Qt.Vertical)

        # Add plot
        self.plots = pg.GraphicsLayoutWidget()
        self.addWidget(self.plots)

        # Claim bottom part (title)
        self.bottom = QSplitter()
        self.bottom.setOrientation(Qt.Horizontal)
        self.addWidget(self.bottom)

        # Add title
        self.title = QtGui.QLabel()
        self.title.setAlignment(QtCore.Qt.AlignCenter)
        self.title.setText('<h2>' + title + ' <\h2>')
        self.desciption = pg.LayoutWidget()
        self.desciption.addWidget(self.title)

        # Add warning information
        self.warning = QtGui.QLabel()
        self.warning.setAlignment(QtCore.Qt.AlignCenter)
        self.desciption.nextRow()
        self.desciption.addWidget(self.warning)
        self.bottom.addWidget(self.desciption)

        # Add a table for fitting information
        self.table = pg.TableWidget()
        self.bottom.addWidget(self.table)

        # Current hdf5 file path
        self.h5_path_shown = None

        # data extractor
        self.data_extractor_manager = DataExtractorManager()

    def update_from_h5(self, h5_path):
        if self.h5_path_shown != h5_path or self.data_extractor_manager.local_data_changed:
            self.h5_path_shown = h5_path
            self.update(h5_path)

    def update_warning(self, warning):
        if warning == '':
            self.warning.setStyleSheet("background-color: lightgreen")
            warning = 'all good'
        else:
            self.warning.setStyleSheet("background-color: red")

        self.warning.setText(warning)

