#!/usr/bin/env python3

import numpy as np
import PyQt5  # make sure pyqtgraph imports Qt5
import pyqtgraph

from artiq.applets.simple import TitleApplet


class MakeHistogramAndPlot(pyqtgraph.PlotWidget):
    def __init__(self, args):
        pyqtgraph.PlotWidget.__init__(self)
        self.args = args

    def data_changed(self, data, mods, title):
        #print(data)
        try:
            y = data[self.args.y][1]
            y = y[~np.isnan(y)]
            #print(self.args.x)
            #if len(y[~np.isnan(y)]) > 5: return
            if self.args.x is None:
                x = 'auto'
            else:
                x = data[self.args.x][1]
        except KeyError:
            return

        # This makes the histogram with the full datasets
        # may be slow so it should be run with a reasonable
        # --update-delay value
        heigs, binsides = np.histogram(y, bins=x, density=True)
        self.clear()
        self.plot(binsides, heigs, stepMode=True, fillLevel=0,
                  brush=(0, 0, 255, 150))
        self.setTitle(title)


def main():
    applet = TitleApplet(MakeHistogramAndPlot)
    applet.add_dataset("y", "Y values")
    applet.add_dataset("x", "Bin boundaries", required=False)
    applet.run()

if __name__ == "__main__":
    main()
