import os
import sys
import pickle
import numpy

from subprocess import Popen, PIPE

import hark


def cartesian2polar(xyz, mode="AZIMUTH"):
    """
    cartesian2polar(x, y, z)
    converts coordinate from xyz to r\theta\phi
    """
    x, y, z = xyz
    r = numpy.sqrt(sum(map(lambda x: x**2, [x, y, z])))
    theta = numpy.arctan2(z, numpy.sqrt(sum(map(lambda x: x**2, [x, y]))))
    phi = numpy.arctan2(y, x)

    return (r, theta, phi)


def r2d(r):
    return 180.0 / numpy.pi * r


class plotQuickSourceKivy(hark.node.PythonNode):
    GUI_SCRIPT_NAME = 'plotQuickSourceKivyGui.py'

    def __init__(self):
        #super().__init__(['SOURCES', 'WINDOW_LENGTH', 'UPDATE_INTERVAL'], ['OUTPUT'])
        super().__init__('SOURCES', '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.points = {}
        self.windowlen = 300

        self.interval = 50
        self.count = 0

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

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

    def gendata(self, sources):
        if isinstance(sources, list):
            for src in sources:
                self.points.setdefault(src.id, [])
                self.points[src.id].append((self.count, r2d(cartesian2polar(src.x)[2])))

        if self.count % self.interval == 0:
            for id in list(self.points.keys()):
                pts = self.points[id]
                if pts[0][0] < self.count - 1000:
                    cdel = self.count - 1000 - pts[0][0]
                    del self.points[id][:cdel]

                    if len(self.points[id]) == 0:
                        del self.points[id]

            self.update({'points': self.points,
                         'trange': (self.count - self.windowlen, self.count)})

    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']
            # check input terminal
        #if not isinstance(kwargs['SOURCES'], list):
        #if (len(kwargs['SOURCES']) > 0):

        #        try:
        #            raise AttributeError("There is an error in the network file. The type of input data to the plotQuickSourceKivy node must be Vector<Source>.")
        #        except AttributeError as e:
        #            print(e)
        self.gendata(kwargs['SOURCES'])

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

