#!/usr/bin/python
# -*- coding: utf-8 -*-

# configure

'''
Created on 2015.9.25
'''

from conf.constants import *
import json
from json import *
import atexit
import redis
#import warnings

# viewer defined
from viewer.user import *
from viewer.menuBar import *
from viewer.statusBar import *
from viewer.mainSet import *
from viewer import logWindow
# model defined
from model import neonReceiver

class mywindow(QtGui.QMainWindow):

    def __init__(self, parent):
        super(mywindow, self).__init__()
        self.parent = parent
        self.setupUi(self)

    def setupUi(self, MainWindow):

        self.myMenuBar = menuBar(self)
        self.setMenuBar(self.myMenuBar)

        self.myStatusBar = statusBar(self)
        self.setStatusBar(self.myStatusBar)

        self.mainSplitter = QtGui.QSplitter(QtCore.Qt.Horizontal, self)

        self.userWidget = CSNSUserInfo(self)
        self.mainSetWidget = CSNSMainSetInfo(self)

        self.mainSplitter.addWidget(self.userWidget)
        self.mainSplitter.addWidget(self.mainSetWidget)

        self.setCentralWidget(self.mainSplitter)
        self.loadConfigure()
        self.setConfigure()
   

        self.ip = "" 
        self.port = 0 
        self.myStatus = 'waiting'
        self.myCommand = 'start'

    def getget(self):
        print "222222"

    def updateDiffractionSimulator(self):
        self.upRightTab.updateDiffractionSimulator()

    def updateDataStreaming(self):
        self.upRightTab.updateDataStreaming()

    def updateProton(self, threadID):
        self.upRightTab.updateProton(threadID)
    
    def getIP(self):
        _ip=None
        try:
	        _ip=self.userWidget.getIP()
        except:
            _ip=None
        return _ip

    def getPort(self):
        _port=None
        try:
	        _port=self.userWidget.getPort()
        except:
	        _port=None
        return _port

    def getDisplay(self):
        screen_resolution = self.parent.desktop().screenGeometry()
        return screen_resolution.width(), screen_resolution.height()

    def loadConfigure(self):
        _confFile='./conf/configure.json'
        _mainWidth, _mainHeight=self.getDisplay()

        if not os.path.exists(_confFile):
            self.mainWidth=_mainWidth
            self.mainHeight=_mainHeight
            self.firstLayout=1
            self.ip="10.1.53.240"
            self.port=9000
            self.mainSplitterLeft=(self.mainWidth + 50) / 7.0
            self.mainSplitterRight=self.mainWidth / 7.0 * 6
        else:
            try:
                layoutParameter = json.loads(open(_confFile, "r").read())
                self.firstLayout= layoutParameter['firstLayout']
                self.mainWidth=layoutParameter['mainWidth']
                self.mainHeight=layoutParameter['mainHeight']
                self.ip=layoutParameter['ip']
                self.port=layoutParameter['port']
                self.mainSplitterLeft=layoutParameter['mainSplitterLeft']
                self.mainSplitterRight=layoutParameter['mainSplitterRight']
            except:
                self.mainWidth=_mainWidth
                self.mainHeight=_mainHeight
                self.firstLayout=1
                self.ip="10.1.53.240"
                self.port=9000

    def setConfigure(self):
        self.resize(self.mainWidth, self.mainHeight)
        self.mainSplitter.setSizes([self.mainSplitterLeft,self.mainSplitterRight])
        self.userWidget.hostTextEdit.setText(self.ip+":"+str(self.port))

    def saveConfigure(self):
        _mainWidth=self.mainSplitter.geometry().width()
        _mainHeight=self.mainSplitter.geometry().height()
        _firstLayout=self.firstLayout+1
        _ip=self.userWidget.getIP()
        _port=self.userWidget.getPort()
        _mainSplitterLeft=self.mainSplitter.sizes()[0]
        _mainSplitterRight=self.mainSplitter.sizes()[1]

        _data = {"mainWidth": _mainWidth, "firstLayout": _firstLayout, "mainHeight": _mainHeight, "mainSplitterLeft":_mainSplitterLeft,"mainSplitterRight":_mainSplitterRight, "ip":_ip, "port":_port }
        
        _confFile='./conf/configure.json'
        if not os.path.exists(_confFile):
            with open(_confFile, "w") as _f:
                json.dump(_data, _f)
        else:
            with open(_confFile, "w") as _f:
                json.dump(_data, _f)

    def setNeonButton(self, value):
	    self.userWidget.setNeonButton(value)
 
    def getNeon(self):
	    self.neonStatus, self.neonServer=self.userWidget.getNeon()
	    return self.neonStatus, self.neonServer
  
    def getStatus(self):
    	return self.myStatus

    def setHeartBeat(self):
    	neonpath="/GPPD/heartbeat/pilot"

    	logging.info("Creating heartbeat thread")
    	heartbeatThread = neonReceiver.setHeartbeat(self.neonServer, 1.0, neonpath, self.getStatus())
    	#heartbeatThread.finished.connect(conf.constants.myapp.exit)
    	logging.info("Starting heartbeat thread")
    	heartbeatThread.setDaemon(True)
    	heartbeatThread.start()
    	logging.info("Start heartbeat successfully")

    def getApp(self):
        return self.parent

    def getCommandButton(self):
        return self.userWidget.hostButton

    def getCommand(self, parent, gui):
        logging.info("Creating Command Thread...")
        self.commandThread = neonReceiver.getCommand(parent, gui)
        logging.info("Start Command Thread successfully")

    @QtCore.pyqtSlot(str)
    def setCommand(self, value):
        self.myCommand=value
        self.setCommandValueLabel(self.myCommand)

    def setCommandValueLabel(self, value):
        return self.userWidget.setCommandValueLabel(value)

    @QtCore.pyqtSlot(object)
    def setProgressData(self, value):
        if value['name']=='proton_charge':
            pass
        elif value['name']=='neutron_counts':
            pass
        elif value['name']=='pulse_counts':
            pass

    @QtCore.pyqtSlot(str)
    def setLog(self, value):
        logging.info(value)
   
    def getCanvasData(self, parent, gui):
        logging.info("Creating Canvas data Thread...")
     
        progressPath='/GPPD/cockpit/progress_setting'        
 
        protonPath='/GPPD/drone/proton_charge'
        neutronPath='/GPPD/workspace/MantidData/neutron_counts'
        pulsePath='/GPPD/drone/pulse_counts'
                
        self.dataThread = neonReceiver.dataThread(parent, gui, self.neonServer, progressPath, protonPath, neutronPath, pulsePath, 1.0)
        logging.info("Start Canvas Data Thread successfully")
    
        self.setProgressBar(0, 200) 

    def setDataPath(self, kwargs):
        self.dataThread.setDataPath(kwargs)

    def getDetectorIndex(self):
        return self.mainSetWidget.upRightTab.detectorPage.getDetectorIndex()

    @QtCore.pyqtSlot(object)
    def setCanvasData(self, value):
        tabIndex = self.dataThread.getTabIndex()
        if tabIndex == 0:
            self.mainSetWidget.upRightTab.histogramPage.updateCanvas(value)            
        elif tabIndex == 1:
            self.mainSetWidget.upRightTab.detectorPage.updateBankCanvas(value)
        elif tabIndex == 2:
            self.mainSetWidget.upRightTab.monitorPage.updateCanvas(value)            
        elif tabIndex == 3:    
            self.mainSetWidget.upRightTab.experimentPage.updateCanvas(value)            
    
    @QtCore.pyqtSlot(object)
    def setMonitorCanvas(self, value):
        xdata = self.dataThread.getMonitorTOF()
        self.userWidget.updateMonitorCanvas(xdata,value)
    
    @QtCore.pyqtSlot(object, object)
    def setUserData(self, _proton, _neutron):
        self.userWidget.setProtonNeutron(_proton, _neutron)

    # set max and min value for progressBar
    def setProgressBar(self, mini, maxi):
        return self.mainSetWidget.createProgressBar(mini, maxi)

    #get current value for progressBar
    def getValue(self):
        value = 100 
        return value

def exit_handler(top):
    top.saveConfigure()

if __name__ == '__main__':
    
    myapp = QtGui.QApplication(sys.argv)
    
    mytop = mywindow(myapp)
    icon = QtGui.QIcon('img/logo.jpg')
    mytop.setWindowIcon(icon)
    mytop.setWindowTitle('GPPD')
    mytop.show()
    time.sleep(0.1)

    # connect neon
    _neonStatus, _neonServer = mytop.getNeon()
    mytop.setNeonButton(_neonStatus)

    # set heartbeat
    if _neonStatus:
        mytop.setHeartBeat()
        mytop.getCommand(myapp, mytop)
        mytop.getCanvasData(myapp, mytop)

    atexit.register(exit_handler, mytop)
    sys.exit(myapp.exec_())
