import wx
import serial
import random

#map function to convert sensor input range to any other range
def map(x,in_min, in_max,out_min, out_max):
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

class MyFrame(wx.Frame):
    def __init__(self, parent, title=""):
        
        super(MyFrame, self).__init__(parent, title=title, size=(800,800))
        # Attach the paint event to the frame
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        # Set the background color
        self.SetBackgroundColour( wx.Colour( 255, 10, 20) )

        # Setup StatusBar
        self.CreateStatusBar()
        self.PushStatusText("inputInterface application")

        # Numbers showing the values
        self.magValueTxt = wx.StaticText(self, wx.ID_ANY, label="mag",pos=(10,10), style=wx.ALIGN_CENTER)
        self.lightValueTxt = wx.StaticText(self, wx.ID_ANY, label="light", pos=(10,25), style=wx.ALIGN_RIGHT)
      
        # Centre and show the frame
        self.Centre()
        self.Show()
       
        
    def OnPaint(self, event=None):
        mag=0
        light=0
        # Create the paint surface
        dc = wx.PaintDC(self)
        # Refresh the display
        self.Refresh()         
        # Get data from serial port until both sensors data acquired
        while (mag==0 or light==0): 
            serialValue=inputDev.readline()
            if serialValue.split(',')[0]=='m': 
                mag = int(serialValue.split(',')[1])
            if serialValue.split(',')[0]=='l': 
                light = int(serialValue.split(',')[1])
        
        mag = map(mag, 0, 1024, 0, 800)
        light = map(light, 0, 1024, 0, 800)
        
        print light
        print "----"
        print mag 
        print "------"
        self.lightValueTxt.SetLabel(str(light))
        self.magValueTxt.SetLabel(str(mag))
        thickness = 4
        border_color = "#FFFFFF"
        fill_color = "#FF944D"
        dc.SetPen(wx.Pen(border_color, thickness))
        dc.SetBrush(wx.Brush(fill_color))
        
        #Draw things!
        
        for i in range (1,light):
        #dc.DrawArc( mag+i+light/i, mag/i-light+i, light/i-mag/i+i, -light+i/i-mag, light/i, mag+i) 
        #dc.DrawSpline([(mag,light),(mag-light, mag-light),(light,light)])
            dc.DrawPoint(random.random()*i,light+random.random()*i)
                    
        for j in range (1,mag):
            dc.DrawPoint(mag/2+random.random()*j, random.random()*j)
                
            

class MyApp(wx.App):
    def OnInit(self):
        #machineSetup()

        self.frame = MyFrame(None, title="inputInterface application")
        self.frame.Show();
        
        return True


if __name__ == "__main__":
    try:
        #inputDev = serial.Serial('COM3', 9600)
        inputDev = serial.Serial('/dev/ttyUSB0', 9600)
    except:
        print "Failed to connect"
        exit()
    app = MyApp(False)
    app.MainLoop()
    inputDev.close()
