"""
Implements a generic plotting interface which plots given figures or from plotting functions and respective data.
AnalysisPlotter is a sub-class of QWidget and can be added to any QLayout.
"""

import matplotlib
import inspect
import logging

from testbeam_analysis.gui.gui_widgets.worker import AnalysisWorker
from PyQt5 import QtWidgets, QtCore

matplotlib.use('Qt5Agg')  # Make sure that we are using QT5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar


class AnalysisPlotter(QtWidgets.QWidget):
    """
    Implements generic plotting area widget. Takes one or multiple plotting functions and their input files
    and displays figures from their return values. Supports single and multiple figures as return values.
    Also supports plotting from multiple functions at once and input of predefined figures. If figures are plotted
    from provided plotting functions, the functions are executed on an extra thread
    """

    startedPlotting = QtCore.pyqtSignal()
    finishedPlotting = QtCore.pyqtSignal()
    exceptionSignal = QtCore.pyqtSignal(Exception, str)

    def __init__(self, input_file=None, plot_func=None, figures=None, thread=None, parent=None, **kwargs):

        super(AnalysisPlotter, self).__init__(parent)

        # Main layout
        self.main_layout = QtWidgets.QVBoxLayout()
        self.setLayout(self.main_layout)

        # Input arguments
        self.input_file = input_file
        self.plot_func = plot_func
        self.figures = figures
        self.kwargs = kwargs

        # External thread provided for plotting; must be QtCore.QThread() or None, if None, no threading.
        # After finishing, thread is deleted
        self.plotting_thread = thread

        if input_file is None and plot_func is None and figures is None:
            msg = 'Need input file and plotting function or figures to do plotting!'