import os
import sys
import argparse
import json
import datetime
import requests
import time
import re
import pprint
import glob
import csv
import epics
from datetime import datetime
from edef import BSABuffer
from PyQt5 import QtWidgets
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import pprint
import numpy as np
sc_bpm_list =[
'BPMS:GUNB:314',
'BPMS:GUNB:925',
'BPMS:L0B:0183',
'BPMS:HTR:120',
'BPMS:HTR:320',
'BPMS:HTR:365',
'BPMS:HTR:460',
'BPMS:HTR:540',
'BPMS:HTR:760',
'BPMS:HTR:830',
'BPMS:HTR:860',
'BPMS:HTR:960',
'BPMS:HTR:980',
'BPMS:COL0:135',
'BPMS:COL0:240',
'BPMS:COL0:260',
'BPMS:COL0:280',
'BPMS:COL0:320',
'BPMS:COL0:400',
'BPMS:COL0:480',
'BPMS:COL0:560',
'BPMS:COL0:640',
'BPMS:COL0:720',
'BPMS:COL0:800',
'BPMS:COL0:880',
'BPMS:COL0:940',
'BPMS:DIAG0:210',
'BPMS:DIAG0:190',
'BPMS:DIAG0:230',
'BPMS:DIAG0:270',
'BPMS:DIAG0:285',
'BPMS:DIAG0:330',
'BPMS:DIAG0:370',
'BPMS:DIAG0:390',
'BPMS:DIAG0:470',
'BPMS:DIAG0:520',
'BPMS:L1B:0283',
'BPMS:L1B:0383',
'BPMS:L1B:H183',
'BPMS:L1B:H283',
'BPMS:BC1B:125',
'BPMS:BC1B:440',
'BPMS:COL1:120',
'BPMS:COL1:260',
'BPMS:COL1:280',
'BPMS:COL1:320',
'BPMS:COL1:400',
'BPMS:COL1:480',
'BPMS:COL1:560',
'BPMS:COL1:640',
'BPMS:COL1:720',
'BPMS:COL1:800',
'BPMS:COL1:880',
'BPMS:COL1:960',
'BPMS:L2B:0483',
'BPMS:L2B:0583',
'BPMS:L2B:0683',
'BPMS:L2B:0783',
'BPMS:L2B:0883',
'BPMS:L2B:0983',
'BPMS:L2B:1083',
'BPMS:L2B:1183',
'BPMS:L2B:1283',
'BPMS:L2B:1383',
'BPMS:L2B:1483',
'BPMS:L2B:1583',
'BPMS:BC2B:150',
'BPMS:BC2B:530',
'BPMS:EMIT2:150',
'BPMS:EMIT2:300',
'BPMS:EMIT2:800',
'BPMS:EMIT2:900',
'BPMS:L3B:1683',
'BPMS:L3B:1783',
'BPMS:L3B:1883',
'BPMS:L3B:1983',
'BPMS:L3B:2083',
'BPMS:L3B:2183',
'BPMS:L3B:2283',
'BPMS:L3B:2383',
'BPMS:L3B:2483',
'BPMS:L3B:2583',
'BPMS:L3B:2683',
'BPMS:L3B:2783',
'BPMS:L3B:2883',
'BPMS:L3B:2983',
'BPMS:L3B:3083',
'BPMS:L3B:3183',
'BPMS:L3B:3283',
'BPMS:L3B:3383',
'BPMS:L3B:3483',
'BPMS:L3B:3583',
'BPMS:EXT:351',
'BPMS:EXT:748',
'BPMS:DOG:120',
'BPMS:DOG:135',
'BPMS:DOG:150',
'BPMS:DOG:165',
'BPMS:DOG:180',
'BPMS:DOG:200',
'BPMS:DOG:215',
'BPMS:DOG:230',
'BPMS:DOG:250',
'BPMS:DOG:280',
'BPMS:DOG:335',
'BPMS:DOG:355',
'BPMS:DOG:405',
'BPMS:DOG:575',
'BPMS:DOG:740',
'BPMS:DOG:910',
'BPMS:BPN13:400',
'BPMS:BPN14:400',
'BPMS:BPN15:400',
'BPMS:BPN16:400',
'BPMS:BPN17:400',
'BPMS:BPN18:400',
'BPMS:BPN19:400',
'BPMS:BPN20:400',
'BPMS:BPN21:400',
'BPMS:BPN22:400',
'BPMS:BPN23:400',
'BPMS:BPN24:400',
'BPMS:BPN25:400',
'BPMS:BPN26:400',
'BPMS:BPN27:400',
'BPMS:BPN28:200',
'BPMS:BPN28:400',
'BPMS:SPD:135',
'BPMS:SPD:255',
'BPMS:SPD:340',
'BPMS:SPD:420',
'BPMS:SPD:525',
'BPMS:SPD:700',
'BPMS:SPD:955',
'BPMS:SLTD:625',
'BPMS:SLTD:895',
'BPMS:SPH:322',
'BPMS:SPH:345',
'BPMS:SPH:420',
'BPMS:SPH:450',
'BPMS:SPH:520',
'BPMS:SPH:600',
'BPMS:SPH:675',
'BPMS:SPH:760',
'BPMS:SPH:840',
'BPMS:SPH:915',
'BPMS:SPH:940',
'BPMS:SLTH:200',
'BPMS:SLTH:220',
'BPMS:SPS:572',
'BPMS:SPS:580',
'BPMS:SPS:640',
'BPMS:SPS:650',
'BPMS:SPS:710',
'BPMS:SPS:770',
'BPMS:SPS:780',
'BPMS:SPS:830',
'BPMS:SPS:840',
'BPMS:SLTS:150',
'BPMS:SLTS:430',
'BPMS:SLTS:460']


'''
for i = 1:nbpms
    tmitswpvs{i} = [ bpms{i} ':TMIT'];
    tmitfwpvs{i} = [ bpms{i} ':FW:TMIT'];
    swscl(i) = lcaGet([ bpms{i} ':QSCL']);
    fwscl(i) = lcaGet([ bpms{i} ':FW:QSCL']);
%     fwsclint(i) = lcaGet([ bpms{i} ':QSCLFWINT']);
%     att1(i) = lcaGet([ bpms{i} ':ATT1']);
%     att2(i) = lcaGet([ bpms{i} ':ATT2']);
    xswpvs{i} = [ bpms{i} ':X'];
    xfwpvs{i} = [ bpms{i} ':FW:X'];
    yswpvs{i} = [ bpms{i} ':Y'];
    yfwpvs{i} = [ bpms{i} ':FW:Y'];
end

'''

class InstantiatePVs():
    def __init__(self,devices:list)->None:
        self._devices = devices
        self.tmit_pvs = {}
        self.fw_tmit_pvs = {}
        self.sw_scl = {}
        self.fw_scl = {}
        self.att1 =  []
        self.att2 = []
        self.get_bpm_scl()
    def get_bpm_scl(self):
        temp_sw_qscl = []
        temp_fw_qscl = []
        for bpm in self._devices:
            temp_sw_qscl.append(bpm+':QSCL')
            temp_fw_qscl.append(bpm+':FW:QSCL')
        got_sw_qscl = epics.caget_many(temp_sw_qscl)
        got_fw_qscl = epics.caget_many(temp_fw_qscl)
        for i in range(len(self._devices)):
            self.sw_scl[self._devices[i]] = got_sw_qscl[i]
            self.fw_scl[self._devices[i]] = got_fw_qscl[i]
        print('\n')
        print('\n')
        print('\n')
        print('Software Scaling Values!!!!!!\n ')
        pprint.pprint(self.sw_scl)
        print('\n')
        print('\n')
        print('\n')
        print('Firmware Scaling Values!!!!!!\n ')
        pprint.pprint(self.fw_scl)

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, x_data, y_data, z_data, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        #setting up plots
        self.main_widget = QtWidgets.QWidget()
        # tmit plot
        self.graphWidget = pg.PlotWidget()
        # z point vs average tmit
        self.zplot = pg.PlotWidget()
        self.setCentralWidget(self.main_widget)
        layout = QtWidgets.QGridLayout(self.main_widget)
        layout.addWidget(self.graphWidget)
        layout.addWidget(self.zplot)


        self.x_data = x_data
        #y_data for tmit plot is a dictionary of bpm tmit values where the key is the bpm name  + :TMIT
        self.y_data = y_data

        self.key_list = list(self.y_data.keys())
        #plot data: x, y values
        for i in range(len(self.key_list)):
            self.graphWidget.plot(self.x_data, self.y_data[self.key_list[i]], pen=(i,len(self.key_list[i]) ))
        
        self.z_data = z_data
        avgs = []
        for key in self.z_data.keys():
            temp = self.z_data[key]
            
            avgs.append(temp)
        self.zplot.plot(list(self.z_data.keys()), avgs)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='This program is a tool for getting/putting IOC, BPM, and TPR values. In addition, there is also functionality built-in for rebooting (-R) or upgrading the Firmware (-F) for IOCs.  Devices are individually searchable or searchable by Linac locations or specialties (-l NC SC COMMON HARD SOFT CAVITY). sample usage '"python bpmTool.py -d ioc -l HTR -v STARTTOD "'' ) 
    parser.add_argument('-d' ,'--referenceDevice', default = 'BPMS:GUNB:314')
    parser.add_argument('-m', '--mode', choices = ['Inclusion','Exclusion','Disable'], default = 'Inclusion')
    parser.add_argument('-n','--num_measurements',default = 25)
    args = parser.parse_args()
    print(args)
    e = datetime.now()
    print('%s' % e)
    np.set_printoptions(precision=16)
    #np.set_printoptions(suppress=True)
    #sc_bpm_list.remove(args.referenceDevice)
    #print(sc_bpm_list)
    
    #setup the BSA Buffer
    signal_buffer = BSABuffer("chris bpm testing", user = "cgarnier")

    #retrieve the buffer number
    num = signal_buffer.number
    print('Buffer Number: ', num)

    #set destination
    signal_buffer.destination_masks = ["SC_BSYD"]

    #build array of z - posititions
    z_array = []
    for bpm in sc_bpm_list:
         z_array.append(bpm+':Z')
    z_positions = epics.caget_many(z_array,connection_timeout = 1.5)


    # Set number of measurements to acquire.  Your value will be clipped to the
    # limits of the BSA system.
    signal_buffer.n_measurements = int(args.num_measurements)
    # line below always prints 1000 even measurements are not 1000 pts
    #print(signal_buffer.n_measurements)
    #using num measurement flag from script
    print('Number of measurements: ', args.num_measurements)

    # You can set a number of shots to average for each measurement.
    # Total number of shots to acquire will be n_measurements * n_avg.
    signal_buffer.n_avg = 1

    # Now, start the acquisition.
    put_pv = 'BSA:SYS0:1:'+str(num)+':DESTMODE'
    put = epics.caput(put_pv, args.mode)
    signal_buffer.start()


    # Wait for the buffer to collect all 500 points.  Alternatively, you can 
    # set a callback function to run when acquisition is complete instead.
    while not signal_buffer.is_acquisition_complete():
        time.sleep(0.1)
       
    #build the list of active_bpms based on if the bpms currently have a tmit value
    #use it to build a array of active bpm z positions
    bpm_tmits = []
    for bpm in sc_bpm_list:
        bpm_tmits.append(bpm+ ':TMIT')
    got_list = epics.caget_many(bpm_tmits)
    active_bpm_tmits=  []
    active_bpm_z = []
    for i in range(len(got_list)):
         if got_list[i] is not None:
              active_bpm_z.append(z_positions[i])
              active_bpm_tmits.append(bpm_tmits[i])
              
    #print(active_bpm_tmits)

    #make dictionarys to store bpm buffer data, and buffer pulse ids, the dictionary key is the bpm tmit pv 
    y_data = {}
    pulse_id_data = {}
    tmit_averages_by_z_pos = {}
    tmit_averages_by_dev = {}
    for i in range(len(active_bpm_tmits)):
       temp = signal_buffer.get_data_buffer(active_bpm_tmits[i])

       #print(type(active_bpm_tmits[i]))
       y_data[active_bpm_tmits[i]]= temp
       #print(temp)
       avg_tmit = np.mean(temp)
       #print(avg_tmit)
       #tmit_averages_by_z_pos[active_bpm_z[i]] = temp
       tmit_averages_by_z_pos[active_bpm_z[i]] = avg_tmit
       temp_dev_name = active_bpm_tmits[i].rsplit(':',1)
    
       tmit_averages_by_dev[temp_dev_name[0]]=avg_tmit
       pulse_id_data[active_bpm_tmits[i]] = epics.caget(active_bpm_tmits[i]+'PIDHST'+str(num),timeout = 1.5)

    #release buffer after data acquisition
    signal_buffer.release()

    #print the bpm tmit pv, pulse id array, and a searchable string if the array is missing values
    pulse_key_list = list(pulse_id_data.keys())
    for i in range(len(pulse_key_list)):
        print(pulse_key_list[i])
        print(pulse_id_data[pulse_key_list[i]])
        if len(pulse_id_data[pulse_key_list[i]]) != int(args.num_measurements):
            print('\n Pulse Id Array is missing elements 000000 \n ')

    #printing a dictionary where pulse ids for an event are the keys, and the value is the count of bpms receiving that pulse id from the buffer 
    #unique pulse ids for the same even trigger the bpm to print
    #count pulses that have at least one mismatch, make an array of mismatch pulse id measurement numbers
    
    failures = 0
    failures_list = []
    failures_devices = [] 
    for i in range(int(args.num_measurements)):
        temp = {}
        for j in range(len(pulse_key_list)):
            #can write code here to omit failing device from continuing to offer its pulse
            if pulse_id_data[pulse_key_list[j]][i] in temp.keys():
                temp[pulse_id_data[pulse_key_list[j]][i]] +=1
            else:
                temp[pulse_id_data[pulse_key_list[j]][i]] =1
                print(pulse_key_list[j])
                

        if len(list(temp.keys())) != 1:
            print(temp)
            print('Failure at measurement: ', i)
            failures +=1
            failures_list.append(i)
    print('Total Failures:', failures, ' found at measurement nums:', failures_list)
    
    #setting up data to pass to plots, make and x value for each measurement
    x_data= []
    for i in range(int(args.num_measurements)):
        x_data.append(i)
 

    key_list = list(y_data.keys())
    app = QtWidgets.QApplication(sys.argv)
    main = MainWindow(x_data = x_data, y_data =y_data, z_data = tmit_averages_by_z_pos)

    #######
    print('\n')
    print('\n')
    print('TMIT Averages from BSA by device!!!')
    pprint.pprint(tmit_averages_by_dev)
    main.show()
    InstantiatePVs(sc_bpm_list)
    sys.exit(app.exec_())