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

# from PyQt4 import QtCore, QtGui
# from PyQt4 import Qt

import json
import datetime

#from presenter.updateStreaming import *
#from model.diffractionSimulator import *
#from model.readData import *
from model import neonReceiver
from viewer.commandThread import *

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
from viewer import canvas

class CSNSUserInfo(QtGui.QWidget):

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

        self.parent = parent
        self.controlThread = None

    def setupUi(self, QWidget):
        self.verticalLayout = QtGui.QVBoxLayout(self)

        self.first = QtGui.QFrame(self)
        self.first.setFrameShape(QtGui.QFrame.StyledPanel)
        self.scrollAreafirst = QtGui.QScrollArea()
        self.scrollAreafirst.setWidgetResizable(True)
        self.scrollAreafirst.setWidget(self.first)

        self.second = QtGui.QFrame(self)
        self.second.setFrameShape(QtGui.QFrame.StyledPanel)
        self.scrollAreasecond = QtGui.QScrollArea()
        self.scrollAreasecond.setWidgetResizable(True)
        self.scrollAreasecond.setWidget(self.second)

        self.third = QtGui.QFrame(self)
        self.third.setFrameShape(QtGui.QFrame.StyledPanel)
        self.scrollAreathird = QtGui.QScrollArea()
        self.scrollAreathird.setWidgetResizable(True)
        self.scrollAreathird.setWidget(self.third)

        self.splitter = QtGui.QSplitter(QtCore.Qt.Vertical)
        self.splitter.addWidget(self.scrollAreafirst)
        self.splitter.addWidget(self.scrollAreasecond)
        self.splitter.addWidget(self.scrollAreathird)
        self.splitter.setSizes([100, 170, 130])

        self.firstGrid = QtGui.QGridLayout(self.first)
        self.secondGrid = QtGui.QGridLayout(self.second)
        self.thirdGrid = QtGui.QGridLayout(self.third)

    	# main verticalLayout
        self.GPPDLabel = QtGui.QLabel('<font color=red>GPPD</font>')
        self.GPPDLabel.setFont(QtGui.QFont('Roman times', 20,
                               QtGui.QFont.Bold))

        self.verticalLayout.addWidget(self.GPPDLabel)
        self.verticalLayout.addWidget(self.splitter)

    	# first Grid
        self.userIDLabel = QtGui.QLabel('UserID: ', self.first)
        self.userIDText = QtGui.QLabel('Lili Yan', self.first)

        self.runIDLabel = QtGui.QLabel('RunID: ', self.first)
        self.runIDText = QtGui.QLabel('00000101', self.first)

        self.proposalLabel = QtGui.QLabel('ProposalID: ', self.first)
        self.proposalText = QtGui.QLabel('GP-2017-000031D', self.first)

    	# second Grid
        self.neonLabel = QtGui.QLabel('NEON', self.second)
        self.neonConnectButton = QtGui.QPushButton('Connect',
                self.second)
        self.neonConnectButton.setFixedSize(QtCore.QSize(80, 30))
        self.neonConnectButton.clicked.connect(self.connectButtonClicked)

        self.hostTextEdit = QtGui.QTextEdit('10.1.53.240:9000', self.second)
        self.hostTextEdit.setReadOnly(True)
        self.hostTextEdit.setFixedSize(QtCore.QSize(100, 30))
        #self.hostTextEdit.setLineWrapColumnOrWidth(150)
        #self.hostTextEdit.setWordWrapMode(QtGui.QTextOption.NoWrap)
        #self.hostTextEdit.setLineWrapMode(QtGui.QTextEdit.FixedPixelWidth)

        
        self.hostButton = QtGui.QPushButton('Disable',
                self.second)
        self.hostButton.setFixedSize(QtCore.QSize(60, 30))
        self.hostButton.clicked.connect(self.hostButtonClicked)

        self.commandLabel = QtGui.QLabel('Command: ', self.second)

        self.commandTimeLabel = QtGui.QLabel('', self.second)
        self.commandValueLabel = QtGui.QLabel('', self.second)
        self.commandValueLabel.setStyleSheet("color:green")
        
        
        self.statusLabel = QtGui.QLabel('Status: ', self.second)
        self.statusTimeLabel = QtGui.QLabel('', self.second)
        self.statusValueLabel = QtGui.QLabel('', self.second)
        self.statusValueLabel.setStyleSheet("color:blue")
 

        # third Grid
        with plt.xkcd():
            self.runCanvas=canvas.xkcdFigure(self)

        self.expTimeLabel = \
            QtGui.QLabel('<font color=red>Running Time:</font>')
        self.expTimeText = QtGui.QLabel('<font color=red></font>')

        self.start=time.time()
        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.setRunTime)
        self.timer.start()

        self.protonLabel = QtGui.QLabel('Proton Charge: ')
        self.protonText = QtGui.QLabel('1.3E6 ')

        self.neutronLabel = QtGui.QLabel('Neutron Counts: ')
        self.neutronText = QtGui.QLabel('5.2E10 ')

        _nline = 0
        self.firstGrid.addWidget(self.userIDLabel, _nline, 0, 1, 1, QtCore.Qt.AlignLeft)
        self.firstGrid.addWidget(self.userIDText, _nline, 1, 1, 1, QtCore.Qt.AlignLeft)

        _nline += 1
        self.firstGrid.addWidget(self.runIDLabel, _nline, 0, 1, 1, QtCore.Qt.AlignLeft)
        self.firstGrid.addWidget(self.runIDText, _nline, 1, 1, 1, QtCore.Qt.AlignLeft)

        _nline += 1
        self.firstGrid.addWidget(self.proposalLabel, _nline, 0, 1, 1, QtCore.Qt.AlignLeft)
        self.firstGrid.addWidget(self.proposalText, _nline, 1, 1, 1, QtCore.Qt.AlignLeft)

        _nline = 0
        self.secondGrid.addWidget(self.neonLabel, _nline, 0, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.secondGrid.addWidget(self.neonConnectButton, _nline, 1, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        _nline += 1
        self.secondGrid.addWidget(self.hostTextEdit, _nline, 0, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.secondGrid.addWidget(self.hostButton, _nline, 1, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        
        _nline += 1
        self.secondGrid.addWidget(self.commandLabel, _nline, 0, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.secondGrid.addWidget(self.commandValueLabel, _nline, 1, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        _nline += 1
        self.secondGrid.addWidget(self.commandTimeLabel, _nline, 0, 1, 2, QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        
        _nline += 1
        self.secondGrid.addWidget(self.statusLabel, _nline, 0, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        self.secondGrid.addWidget(self.statusValueLabel, _nline, 1, 1, 1, QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)
        _nline += 1
        self.secondGrid.addWidget(self.statusTimeLabel, _nline, 0, 1, 2, QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop)

        _nline += 1
        self.thirdGrid.addWidget(
            self.expTimeLabel,
            _nline,
            0,
            1,
            1,
            QtCore.Qt.AlignLeft,
            )
        self.thirdGrid.addWidget(
            self.expTimeText,
            _nline,
            1,
            1,
            1,
            QtCore.Qt.AlignLeft,
            )
        _nline += 1
        self.thirdGrid.addWidget(
            self.protonLabel,
            _nline,
            0,
            1,
            1,
            QtCore.Qt.AlignLeft,
            )
        self.thirdGrid.addWidget(
            self.protonText,
            _nline,
            1,
            1,
            1,
            QtCore.Qt.AlignLeft,
            )
        _nline += 1
        self.thirdGrid.addWidget(
            self.neutronLabel,
            _nline,
            0,
            1,
            1,
            QtCore.Qt.AlignLeft,
            )
        self.thirdGrid.addWidget(
            self.neutronText,
            _nline,
            1,
            1,
            1,
            QtCore.Qt.AlignLeft,
            )
        _nline += 1
        self.thirdGrid.addWidget(
            self.runCanvas,
            _nline,
            0,
            1,
            2,
            QtCore.Qt.AlignCenter,
            )
        self.thirdGrid.addItem(QtGui.QSpacerItem(-1, -1,
                               QtGui.QSizePolicy.Ignored,
                               QtGui.QSizePolicy.Expanding), 2, 0)

        timen=str(datetime.datetime.now())
        self.setCommandTimeLabel(timen)

        self.setCommandValueLabel('<font color=green>Start</font>')
        
        #timen=timen+21.4
        self.setStatusTimeLabel(timen)
        self.setStatusValueLabel('<font color=red>Running</font>')

    def hostButtonClicked(self):
        if self.hostButton.text() == 'Enable':
            logging.info("1")
            self.hostTextEdit.setReadOnly(True)      
            self.hostButton.setText('Disable')
            logging.info("HOST Editor disabled.")
        elif self.hostButton.text() == 'Disable':
            logging.info("2")
            self.hostButton.setText('Enable')       
            self.hostTextEdit.setReadOnly(False)      
            logging.info("HOST Editor enabled.")

    def setNeonButton(self, value):
        if value:
            self.neonConnectButton.setText('Disconnect')
        else:
            self.neonConnectButton.setText('Connect')

    def getNeon(self):
        status=False
        server=None

        _timeout=10
        _ip=self.getIP()
        _port=self.getPort()
        if _ip is None or _port is None:
           logging.ERROR("NEON is not configured")
        else:
            _r=neonReceiver.connectNeon(_ip, _port, _timeout)
            status=_r.getStatus()
            server=_r.getServer()
        
        return status, server

    def connectButtonClicked(self):
        if self.neonConnectButton.text() == 'Connect':
            status, server = self.getNeon()
            if status:
                self.neonConnectButton.setText('Disconnect')
                logging.info("NEON connected.")

        elif self.neonConnectButton.text() == 'Disconnect':
            status=False
            server=None
            self.neonConnectButton.setText('Connect')
            logging.info("NEON disconnected.")

    def setCommandTimeLabel(self, time):
        self.commandTimeLabel.setText(time)

    def setCommandValueLabel(self, value):
        self.commandValueLabel.setText(value)
    
    def setStatusTimeLabel(self, time):
        self.statusTimeLabel.setText(time)

    def setStatusValueLabel(self, value):
        self.statusValueLabel.setText(value)
    
    def setRunTime(self):
        _during=int(time.time()-self.start)
        self.expTimeText.setText(str(_during))

    def getIP(self):
        _host=self.hostTextEdit.toPlainText().split(":")
        return _host[0]

    def getPort(self):
        _host=self.hostTextEdit.toPlainText().split(":")
        return int(_host[1])

    def setProtonNeutron(self, _proton, _neutron):
        self.protonText.setText(str(_proton))
        self.neutronText.setText(str(_neutron))

    def updateMonitorCanvas(self, xdata, ydata):
        try:
            self.runCanvas.ax.clear()
            #self.runCanvas.ax.set_xdata(xdata)
            #self.runCanvas.ax.set_ydata(ydata)
            self.runCanvas.ax.plot(xdata, ydata, color="g")
            self.runCanvas.ax.relim()
            self.runCanvas.ax.autoscale_view()
            self.runCanvas.draw()
            self.runCanvas.flush_events()
        except:
            pass
    '''
    def createDataThread(self):
        _neonStatus, _neonServer = self.getNeon()
        self.setNeonButton(_neonStatus)
        
        if _neonStatus:
            mytop.setHeartBeat()
            mytop.getCommand(myapp, mytop)
            mytop.getCanvasData(myapp, mytop)
    '''
