import numpy as np

from .DataExtractorLyse import DataExtractorManager
from .WidgetPlot import WidgetPlot

import pyqtgraph as pg
from pyqtgraph import OrderedDict
from PyQt5.QtWidgets import QLabel, QLineEdit
from pyqtgraph import Qt
from pyqtgraph.Qt import QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import QRegExpValidator
from PyQt5.QtCore import QRegExp

from PIL import ImageColor


class Widget1DLivingPlot(WidgetPlot):

    def __init__(self, title, x_data_path=None, y_data_path=None, x_in_results=False, y_in_results=False, **kwargs):

        super().__init__(title, **kwargs)

        # set data extractor
        if x_data_path is not None:
            self.x_data_extractor_manager = DataExtractorManager(x_data_path)
            self.x_data_extractor_manager.add_data_extractor('warning', 'single', (x_data_path[0], 'warning'))
            if x_in_results:
                self.x_data_extractor_manager.add_data_extractor('x', 'single', x_data_path)
            else:
                self.x_data_extractor_manager.add_data_extractor('x', 'global', x_data_path)
        else:
            self.x_data_extractor_manager = None

        self.y_data_extractor_manager = DataExtractorManager(y_data_path)
        self.y_data_extractor_manager.add_data_extractor('warning', 'single', (y_data_path[0], 'warning'))
        if y_in_results:
            self.y_data_extractor_manager.add_data_extractor('y', 'single', y_data_path)
        else:
            self.y_data_extractor_manager.add_data_extractor('y', 'global', y_data_path)

        self.aximg = self.plots.addPlot(title="")
        self.img = pg.PlotCurveItem()
        self.aximg.setClipToView(True)
        self.aximg.setDownsampling(mode='peak')
        self.aximg.addItem(self.img)

        self.x = np.empty(100)
        self.y = np.empty(100)
        self.current_data_length = 0

    def update(self, h5_path):

        if self.current_data_length >= self.x.shape[0]:
            tmp = self.x
            self.x = np.empty(self.x.shape[0] * 2)
            self.x[:tmp.shape[0]] = tmp
            tmp = self.y
            self.y = np.empty(self.y.shape[0] * 2)
            self.y[:tmp.shape[0]] = tmp

        if self.x_data_extractor_manager is not None:
            x_data = self.x_data_extractor_manager.get_data(h5_path)
            self.x[self.current_data_length] = x_data['x']
        else:
            self.x[self.current_data_length] = self.current_data_length
        y_data = self.y_data_extractor_manager.get_data(h5_path)
        self.y[self.current_data_length] = y_data['y']

        print(y_data['y'])
        self.img.setData(x=self.x[:self.current_data_length], y=self.y[:self.current_data_length])
        self.current_data_length = self.current_data_length + 1



