
import numpy
import os, sys, pickle
import multiprocessing as mp
from subprocess import Popen, PIPE

import hark


class plotQuickWaveformKivy(hark.node.PythonNode):
    GUI_SCRIPT_NAME = 'plotQuickWaveformKivyGui.py'

    def __init__(self):
        #super().__init__(['WAVE', 'WINDOW_LENGTH', 'UPDATE_INTERVAL'], ['OUTPUT'])
        super().__init__('WAVE', 'OUTPUT')

        script_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), self.GUI_SCRIPT_NAME)
        python_exec = sys.executable
        self.proc = Popen([python_exec, script_path], stdin=PIPE)

        self.showwave = None
        self.windowlen = 20000
        self.wavelen = 0
        self.cursorskip = 5000
        self.max = 100

        self.interval = 5

        self.running = True
        self.count = 0

    def __del__(self):
        self.proc.kill()

    def update(self, data):
        pickle.dump(data, self.proc.stdin)

    def gendata(self, data):
        wave = data
        self.showwave = wave if self.showwave is None else numpy.concatenate((self.showwave, wave), axis=1)
        self.wavelen += wave.shape[1]

        if self.count % self.interval == 0 and self.showwave.shape[1] > self.windowlen:
            cursor = self.cursorskip * ((self.wavelen - self.windowlen) // self.cursorskip)
            self.showwave = self.showwave[:, -(self.wavelen - cursor):]

            self.max = max(self.max, int(self.showwave.max()) + 1)

            self.update({'wave':     self.showwave[:, :self.windowlen],  # self.showwave
                         'offset':   cursor,  # max(0, self.wavelen - self.windowlen),
                         'channels': self.showwave.shape[0],
                         'trange':   (cursor, cursor + self.windowlen),  # (self.wavelen - self.windowlen, self.wavelen),
                         'yrange':  (-self.max, self.max),
                         })

    def forward(self, **kwargs):
        if self.count == 0:
            # set Parameters
            if 'WINDOW_LENGTH' in kwargs:
                if isinstance(kwargs['WINDOW_LENGTH'], int):
                    self.windowlen = kwargs['WINDOW_LENGTH']
            if 'UPDATE_INTERVAL' in kwargs:
                if isinstance(kwargs['UPDATE_INTERVAL'], int):
                    self.interval = kwargs['UPDATE_INTERVAL']
            if 'INITIAL_AMP_SCALE' in kwargs:
                if isinstance(kwargs['INITIAL_AMP_SCALE'], int):
                    self.max = kwargs['INITIAL_AMP_SCALE']
        #    # check input terminal
        #    if not isinstance(kwargs['WAVE'], numpy.ndarray):
        #        try:
        #            raise AttributeError("There is an error in the network file. The type of input data to the plotQuickWaveformKivy node must be Matrix<float>.")
        #        except AttributeError as e:
        #            print(e)
        self.gendata(kwargs['WAVE'])

        self.count += 1
        return {'OUTPUT': kwargs['WAVE']}

