
import numpy
import os, sys, pickle
from subprocess import Popen, PIPE

import hark


class plotQuickMusicSpecKivy(hark.node.PythonNode):
    GUI_SCRIPT_NAME = 'plotQuickMusicSpecKivyGui.py'

    def __init__(self):
        #super().__init__(['SPECTRUM', 'WINDOW_LENGTH', 'UPDATE_INTERVAL'], ['OUTPUT'])
        super().__init__('SPECTRUM', '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.spectrum = numpy.array([])
        self.windowlen = 100

        self.interval = 1
        self.count = 0

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

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

    def gendata(self, data):
        tmp = data[numpy.newaxis, :]
        if tmp.sum() == 0:
            return

        if len(self.spectrum) == 0:
            self.spectrum = numpy.zeros(((self.windowlen - 1), len(data)))
        self.spectrum = numpy.r_[self.spectrum, tmp]

        if len(self.spectrum) > self.windowlen:
            self.spectrum = self.spectrum[-self.windowlen:, :]

        if self.count % self.interval == 0:
            self.update({'spectrum': self.spectrum, 'offset': self.count})

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

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

