# -*- coding: iso-8859-1 -*-
import caGetInt
import sys
import os
import numpy as np
from PyQt5 import QtWidgets
from widgetIncExcMask import*
from collections import OrderedDict
import time
from epics import PV

class EventCodeIncExcMask(QtWidgets.QWidget):
  def __init__(self):
    super(EventCodeIncExcMask, self).__init__()
    self.initUI()

  def initUI(self):
    self.setGeometry(100, 100, 100, 70)
    self.scrollArea = QtWidgets.QScrollArea(self)
    self.scrollArea.setWidgetResizable(True)
    self.scrollArea.setGeometry(0,0,950,900)
    self.scrollAreaWidgetContents = QtWidgets.QWidget(self.scrollArea)
    self.scrollAreaWidgetContents.setGeometry(0, 0, 900, 1200)
    self.scrollArea.setWidget(self.scrollAreaWidgetContents)
    self.show()

    
    #Macros function reading
    self.evnt=''
    self.mask_num=0
    self.macrosPass()
    if self.evnt == '':
        print "Please check back macros "
    
    self.grid = QtWidgets.QGridLayout(self.scrollAreaWidgetContents)
    listWidget=[]
    
    self.num_PV=0
    self.PV_group={}
    self.PV_group= self.selectPV()

    #To order PV's dictionary :
    self.PV_group=OrderedDict(sorted(self.PV_group.items()))

    row_count=0
    row_count+=1
    self.maxPVMask=150 #150 is Max number of PV in the interface    
    self.vbox = QtWidgets.QHBoxLayout()
    #Inclusion and Exlucion Masks declaration
    self.Title0=QtWidgets.QLabel(str(self.evnt)+" Event Code")
    self.Title0.setStyleSheet("font-size:18px;color:black;")
    self.grid.addWidget(self.Title0,0,0)
    self.Title1=QtWidgets.QLabel(self.mask_num+"    Inclusion and")
    self.Title1.setStyleSheet("font-size:18px;color:black;")
    self.grid.addWidget(self.Title1,0,1)
    self.Title2=QtWidgets.QLabel( "Exclusion Mask Setup")
    self.Title2.setStyleSheet("font-size:18px;color:black;")
    self.grid.addWidget(self.Title2,0,2)

    #Up label on Radio Button
    none="~    &nbsp;     "
    self.leg=QtWidgets.QLabel(" <font color='black'> &nbsp;  ~ &nbsp; <font><font color='#4de48b'> I &nbsp;  <font>  <font color='#3e91f7'> E &nbsp; <font>")
    self.leg.setStyleSheet("font-size:16px;font-weight:600;")
    self.grid.addWidget(self.leg,1,0)
    self.leg1=QtWidgets.QLabel(" <font color='black'> &nbsp;  ~ &nbsp; <font><font color='#4de48b'> I &nbsp;  <font>  <font color='#3e91f7'> E &nbsp; <font>")
    self.leg1.setStyleSheet("font-size:16px;font-weight:600;")
    self.grid.addWidget(self.leg1,1,1)
    self.leg2=QtWidgets.QLabel(" <font color='black'> &nbsp;  ~ &nbsp; <font><font color='#4de48b'> I &nbsp;  <font>  <font color='#3e91f7'> E &nbsp; <font>")
    self.leg2.setStyleSheet("font-size:16px;font-weight:600;")
    self.grid.addWidget(self.leg2,1,2)
    self.leg3=QtWidgets.QLabel(" <font color='black'> &nbsp;  ~ &nbsp; <font><font color='#4de48b'> I &nbsp;  <font>  <font color='#3e91f7'> E &nbsp; <font>")
    self.leg3.setStyleSheet("font-size:16px;font-weight:600;")
    self.grid.addWidget(self.leg3,1,3)
    self.leg4=QtWidgets.QLabel(" <font color='black'> &nbsp;  ~ &nbsp; <font><font color='#4de48b'> I &nbsp;  <font>  <font color='#3e91f7'> E &nbsp; <font>")
    self.leg4.setStyleSheet("font-size:16px;font-weight:600;")
    self.grid.addWidget(self.leg4,1,4)


    
    #Read actual PV value
    ind=0
    self.masks_inc=['I','J','K','L','M']
    self.masks_exc=['N','O','P','Q','R']
    self.bit_inc=[]
    self.bit_exc=[]
    while ind<5: #5 is the number of modifier that we set
        self.bit_inc.append(caGetInt.getNum("EVNT:"+str(self.SYS)+":1:"+self.evnt+"CHCK."+str(self.masks_inc[ind])))
        self.bit_exc.append(caGetInt.getNum("EVNT:"+str(self.SYS)+":1:"+self.evnt+"CHCK."+str(self.masks_exc[ind])))
        ind+=1
    
    #Make widgets 
    countPVMask=0
    while countPVMask < len(self.PV_group) :
        self.flag=0
        PVname=self.PV_group.keys()[countPVMask]
        listWidget.append(widgetIncExcMask(str(countPVMask), countPVMask, countPVMask, self.PV_group, self.SYS, self.evnt, self.bit_inc, self.bit_exc))
        listWidget[countPVMask].PV_label.setScaledContents(0)
        listWidget[countPVMask].code=countPVMask
        countPVMask+=1
    self.maxPVMask=countPVMask
    countPVMask=0
    c_count=0
    row_count=2    
    #Add widget to the interface
    while countPVMask < self.maxPVMask :
        if row_count>22:
            c_count+=1
            row_count=2 
        self.flag=0
        self.grid.addWidget(listWidget[countPVMask], row_count , c_count)
        row_count+=1
        countPVMask+=1
    row_count+=countPVMask
    self.flag=1
    self.move(0, 0)
    self.setWindowTitle('Inclusion and Exclusion Mask Setup')
    self.resize(950, 1200)
    self.show()


  #Read by command line macro's variables
  def macrosPass(self):
    a = sys.argv[1:]
    count = 0
    while count < len(a) :
        if a[count] == 'SYS':
            self.SYS = a[count + 1]
        if a[count] == 'evnt':
            self.evnt = a[count + 1]
        if a[count] == 'mask_num':
            self.mask_num = a[count + 1]
        count += 1

  def findElem(self, array, element):
    pos = 0
    count = 0
    for el in array:
        if el is element:
            pos = count
        count += 1
    return pos
      
  #Make a dictionary of used PV's
  def selectPV (self):
    maxNumPV = 141
    check = 1
    PV_group = {}
    name = []
    bitP = []
    t = time.time()
    #Dictionary declaration
    while( check < maxNumPV ):
        name.append(PV("PNBN:"+str(self.SYS)+":"+str(check)+":NAME"))
        bitP.append(PV("PNBN:"+str(self.SYS)+":"+str(check)+":BITP"))
        check += 1
    check = 1
    while(check < maxNumPV-1):
        name_v = name[check].get()
        bitPv = bitP[check].get()
        if name_v != '':
            if bitPv > 31:
                  PV_group.update({name_v : bitPv})
        self.num_PV += 1
        check += 1
    t = time.time() - t
    print('Connection + get, TIME: ' + str(t) + 's')
    return PV_group
      
################MAIN##########################
def main():
    app = QtWidgets.QApplication(sys.argv) 
    app.setApplicationName('EventCodeIncExcMaskWindow')
    ex = EventCodeIncExcMask()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
