
import kivy
kivy.require('1.8.0')

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window
from kivy.clock import Clock
from kivy.utils import get_color_from_hex as rgb

from kivy.graphics import Line, RenderContext, Color, Rectangle
from kivy.graphics.texture import Texture
from kivy_garden.graph import Graph, LinePlot

import numpy
import pickle
import sys
import threading

from plotQuickImageGui import KivyImageGraph

import queue

BUF_SIZE = 10
q = queue.Queue(BUF_SIZE)


class KivyMusicSpecCodeGraph(KivyImageGraph):
    def __init__(self):
        super(KivyMusicSpecCodeGraph, self).__init__()
        self.flabel = 'Source number'

    def do_plot(self):
        while True:
            dat = pickle.load(sys.stdin.buffer)
            q.put(dat)

    def read_queue(self, dt):
        if q.empty():
            # print("empty")
            pass

        else:
            item = q.get()
            spectrum = numpy.array(item['spectrum'], dtype=numpy.float32)
            self.setImage(spectrum, offset=item['offset'])


class KivyMusicSpecCodeApp(App):
    def on_start(self):
        threading.Thread(target=self.root.do_plot).start()
        Clock.schedule_interval(self.root.read_queue, 0.001)

    def build(self):
        self.title = 'plotQuickMusicSpec'
        return KivyMusicSpecCodeGraph()


if __name__ == '__main__':
    KivyMusicSpecCodeApp().run()

