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 WidgetAnalysePanel(QSplitter):
    def __init__(self, **kwargs):

        super().__init__(**kwargs)

        self.setOrientation(Qt.Vertical)

        # Add title
        self.title = QtGui.QLabel()
        self.title.setAlignment(QtCore.Qt.AlignCenter)
        self.title.setText('<h2>' + 'Analyse and Fitting' + ' <\h2>')
        self.title.setFixedHeight(30)
        self.addWidget(self.title)

        self.bottom = QSplitter()
        self.addWidget(self.bottom)

        self.absorption_image = None
        self.absorption_image_plot = None
        self.absorption_image_atom_number = None

    def update_absorption_imaging_atom_number(self):
        x, y = self.absorption_image_plot.roi.pos()
        x_span, y_span = self.absorption_image_plot.roi.size()

        x = int(x)
        y = int(y)
        x_span = int(x_span)
        y_span = int(y_span)

        self.absorption_image.image_absorption = self.absorption_image_plot.data_image

        self.absorption_image.select_effective_data((x, y), (x_span, y_span))

        self.absorption_image.get_atom_number(force_to_run=True)

        self.absorption_image_atom_number.setText(str(self.absorption_image.atom_number))

    def add_absorption_imaging(self, absorption_image, widget_fake_color_plot):

        self.absorption_image = absorption_image
        self.absorption_image_plot = widget_fake_color_plot
        self.absorption_image.image_absorption = self.absorption_image_plot.data_image

        self.absorption_image_plot.roi.sigRegionChanged.connect(self.update_absorption_imaging_atom_number)
        self.absorption_image_plot.analyse_panel_update = self.update_absorption_imaging_atom_number

        current_box = QSplitter()
        current_box.setOrientation(Qt.Vertical)

        title = QLabel('Absorption Imaging')
        title.setAlignment(Qt.AlignCenter)
        title.setFixedHeight(30)
        current_box.addWidget(title)

        atom_number_box = QSplitter()
        atom_number_box.setOrientation(Qt.Horizontal)
        atom_number_title = QLabel('  Atom Number: ')
        atom_number_title.setAlignment(Qt.AlignCenter)
        self.absorption_image_atom_number = QLineEdit()
        self.absorption_image_atom_number.setText(str(absorption_image.atom_number))
        self.absorption_image_atom_number.setReadOnly(True)
        atom_number_title.setFixedHeight(30)
        self.absorption_image_atom_number.setFixedHeight(30)
        atom_number_box.addWidget(atom_number_title)
        atom_number_box.addWidget(self.absorption_image_atom_number)
        current_box.addWidget(atom_number_box)

        next_box = QSplitter()
        next_box.addWidget(current_box)
        self.bottom.addWidget(next_box)
        self.bottom = next_box


