from PyQt4 import QtGui, QtCore
import sys
import logging
import cv2
import numpy as np
import png
import pigpio
from PiRapidStream import PiRapidStream
from TheSquaire import TheSquaire
from Guiv2 import Ui_MainWindow, OutLog
from PyQt4.phonon import Phonon
from SubMenus import SubMenus
import serial
import time



class main(QtGui.QMainWindow):

    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        #self.ui.GCodeInput.returnPressed() 

        #self.ui.bigPic = QtGui.QWidget()
        #self.ui.myPic = QtGui.QPixmap('pic.png')
        #self.ui.bigPic.addWidget(self.myPic)
        global vs
        global gp
        gp = pigpio.pi()
        vs = PiRapidStream(resolution=(576,512),fps=30,form='yuv',exp=30000,gain=1.15)
        vs.startcapt()
        self.videoT = videoThread()
        self.videoT.start()
        self.setupSignals()
        
        #vp = Phonon.VideoPlayer()
        
        
        sys.stdout = OutLog(self.ui.ConsoleBox)
        sys.stderr = OutLog(self.ui.ConsoleBox)

        global ser 
        ser = serial.Serial("/dev/ttyACM0", 115200, timeout = 1)
        print(ser.readall())

        #self.ui.frameCamera.addWidget() #170, 10, 640, 480
        #vp.show()
        #media = Phonon.MediaSource('katzi.mp4')
        #vp.load(media)
        #vp.play()
        #png.from_array(vs.frame, 'L').save('output.png')
        bytearr=vs.frame.data
        height, width = vs.frame.shape
        qImg=QtGui.QImage(bytearr, width, height, QtGui.QImage.Format_Indexed8)
        #pixmap = QtGui.QPixmap(png.from_array(vs.frame, 'L'))
        #pixmap = pixmap.scaled(130, 130)
        #self.ui.icon4.addPixmap(QtGui.QPixmap("output.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ui.icon4.addPixmap(QtGui.QPixmap.fromImage(qImg), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ui.buttonPicture.setIcon(self.ui.icon4)
        self.ui.buttonPicture.setIconSize(QtCore.QSize(130, 130))
        #self.ui.labelPicture.setPixmap(pixmap)

        self.ui.PiCAMStream.setPixmap(QtGui.QPixmap.fromImage(qImg))

        #log_handler = QPlainTextEditLogger(self.ui.ConsoleBox)
        #logging.getLogger().addHandler(log_handler)
        

    def setupSignals(self):
        self.ui.setLiquidButton.clicked.connect(lambda: self.dspVal(self.ui.lcdLiquidAmount, self.ui.doubleSpinBoxLiquid))
        self.ui.setTimeIntervallButton.clicked.connect(lambda: self.dspVal(self.ui.lcdTimeIntervall, self.ui.doubleSpinBoxTime))
        self.ui.buttonLeft.clicked.connect(self.moveLeft)
        self.ui.buttonRight.clicked.connect(self.moveRight)
        self.ui.buttonUp.clicked.connect(self.moveUp)
        self.ui.buttonDown.clicked.connect(self.moveDown)

        self.ui.buttonTakePicture.clicked.connect(self.TakePicture)
        self.ui.buttonSavePicture.clicked.connect(self.SavePicture)
        self.ui.buttonOpenPicture.clicked.connect(self.OpenPicture)

        #self.ui.pushButton.clicked.connect(self.GCodeSend)
        self.ui.PiCAMStream.connect(self.videoT, QtCore.SIGNAL('newQImage(QImage)'),self.updatePixmap)

    def dspVal(self, lcd, spBox):
        lcd.display(spBox.value())

    def updatePixmap(self, image):
        pixmap = QtGui.QPixmap.fromImage(image)
        self.ui.PiCAMStream.setPixmap(pixmap)
        
    def TakePicture(self):
        img=QtGui.QImage(vs.frame.data, 576, 512, QtGui.QImage.Format_Indexed8)      
        self.ui.icon4.addPixmap(QtGui.QPixmap.fromImage(img), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.ui.buttonPicture.setIcon(self.ui.icon4)
        self.ui.buttonPicture.setIconSize(QtCore.QSize(130, 130))

    def SavePicture(self):
        pass
        print("SPARTA, THIS IS SPARTA")
        for x in range(0, 1000000, 10000):
            gp.hardware_PWM(18, 28000, x)
            print("This was focus \n",x)
            #time.sleep(0.5)

        gp.hardware_PWM(18, 28000, 0)
        gp.stop()

    def OpenPicture(self):
        gp.hardware_PWM(18, 28000, 0)
        

    def on_click(self):
        self.bigPic = QtGui.QDialog()
        self.myPic = QtGui.QPixmap('pic.png')
        self.bigPic.show(self.myPic)

    def startGConsole(self):
        userActionKeyboard = input()        
        while(userActionKeyboard != "PP"):
            ser.write(userActionKeyboard + "\n")
            ser.readline()
    
    def moveLeft(self):
        ser.write("G0 Y10\n")

    def moveRight(self):
        ser.write("G0 Y-10\n")
        print(ser.readline())

    def moveUp(self):
        ser.write("G0 X10\n")

    def moveDown(self):
        ser.write("G0 X-10\n")

    def resetPos(self):
        ser.write("G28 \n")

    def GCodeSend(self):
        text = self.ui.GCODEINPUT.text()
        print("%s" % text)

    def keyPressEvent(self, e):
        

        #print(e.key())     
        if e.key() == QtCore.Qt.Key_Escape:
            self.close()
        elif e.key() == QtCore.Qt.Key_A:
            self.moveLeft()
        elif e.key() == QtCore.Qt.Key_D:
            self.moveRight()
        elif e.key() == QtCore.Qt.Key_W:
            self.moveUp()
        elif e.key() == QtCore.Qt.Key_S:
            self.moveDown()
        elif e.key() == QtCore.Qt.Key_R:
            self.resetPos()
        elif e.key() == QtCore.Qt.Key_Return:
            data = self.ui.GCODEINPUT.text()            
            print("%s" % data)

class videoThread(QtCore.QThread):

    def __init__(self):
        super(videoThread,self).__init__()
        
    def run(self):
            while True:
                image = QtGui.QImage(vs.frame.data, 576, 512, QtGui.QImage.Format_Indexed8) 
                self.emit(QtCore.SIGNAL('newQImage(QImage)'), image)
                #print("Herre")
                time.sleep(0.2)
                


if __name__ == "__main__":
    #import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = main()
    MainWindow.show()
    sys.exit(app.exec_())

