import os
import json
import subprocess
from datetime import datetime
from edef import BSABuffer
from qtpy import QtCore
from pydm import Display
from pprint import pprint
from qtpy.QtWidgets import QApplication, QVBoxLayout, QLabel, QTabWidget, QGroupBox, QWidget, QHBoxLayout, QScrollArea, QGridLayout, QFrame, QSpacerItem, QSizePolicy, QComboBox,QTableWidget,QHeaderView,QTableWidgetItem
from pydm.widgets import PyDMRelatedDisplayButton, PyDMCheckbox, PyDMLabel, PyDMPushButton, PyDMSlider, PyDMTabWidget, PyDMLineEdit, PyDMEnumComboBox, PyDMEmbeddedDisplay
from pydm.utilities.stylesheet import GLOBAL_STYLESHEET
from edmbutton import PyDMEDMDisplayButton
from collections import defaultdict
from functools import partial
import pyqtgraph as pg
import epics
import time
import numpy as np
import pprint
import math
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'
'''
class MainDisplay(Display):
    def __init__(self, parent=None, args=[], macros=None):
        super(MainDisplay, self).__init__(parent=parent, args=args, macros=macros)
        self.default_size = (1425, 1250)
        self.bpm_dir= os.path.dirname(os.path.realpath(__file__))
        self.bpm_stylesheet= os.path.join(self.bpm_dir, 'bpm_display_stylesheet.qss')
        self.app = QApplication.instance()
        self.app.installEventFilter(self)
        #self.append_stylesheet(self.bpm_stylesheet)
        if macros:
            self.class_macros = macros
            print(macros)
            self.macros()
        self.ref_bpm = 'BPMS:GUNB:314'
        self.setup_bsa_buffer()
        self.setup_ui()
        self.resize(*self.default_size)
        self.setup_dropdown_info()
        self.setup_plot_grid()
        self.setup_control_grid()
        self.iron_bpms()

        #self.installEventFilter(self)
    def ui_filepath(self):
        return None
    def append_stylesheet(self, qss_file):
        with open(qss_file) as f:
            curr_sheet = self.styleSheet()
            new_sheet = f.read()
            self.setStyleSheet(curr_sheet + new_sheet)
    def make_channel(self, dev, field):
        return 'ca://{}:{}'.format(dev, field)
    def setup_header(self):
        header_label = QLabel('BPM IRONING')
        return header_label
    def load_data_table_signal(self,index):
        self.data_table.clearContents()
        selected_item = self.dropdown.currentText()
        if selected_item == 'Average TMIT From BSA':
            if hasattr(self.bsa_buffer,'bpm_tmit_averages_dictionary'):
                self.load_data_table_from_dictionary(self.bsa_buffer.bpm_tmit_averages_dictionary)
        if selected_item == 'FW QSCL':
            if hasattr(self.plot_grid,'fw_scl_pvs'):
                self.load_data_table_from_dictionary(self.plot_grid.fw_scl_pvs)
        if selected_item == 'SW QSCL':
            if hasattr(self.plot_grid,'sw_scl_pvs'):
                self.load_data_table_from_dictionary(self.plot_grid.sw_scl_pvs)
        if selected_item == 'Wrong Size PIDs':
            if hasattr(self,'wrong_size_pid'):
                self.load_data_table_from_dictionary(self.wrong_size_pid)
        if selected_item  ==  'Counts of BPMs per Unique PID':
             if hasattr(self,'bpm_pid_counts_by_meas'):
                 self.load_data_table_from_nested_dictionary(self.bpm_pid_counts_by_meas)
        if selected_item  ==  'Dev Names of PIDs by Measurement':
            if hasattr(self,'bpm_pid_devs_by_meas'):
                self.load_data_table_from_nested_dictionary(self.bpm_pid_devs_by_meas)
    def load_data_table_from_dictionary(self,pv_dict):
        ### will need to fix this to make it quicker but for now just do the same thing with QLabels
        self.data_table.setRowCount(len(pv_dict))
        self.data_table.setColumnCount(2)
        for row, (key,value) in enumerate(pv_dict.items()):
            key = str(key)
            value = str(value)
            key_item = QTableWidgetItem(key)
            value_item = QTableWidgetItem(value)
            self.data_table.setItem(row,0,key_item)
            self.data_table.setItem(row,1,value_item)
        self.data_table.resizeColumnsToContents()
    def load_data_table_from_nested_dictionary(self,nested_dict):
        #print(nested_dict)
        
        self.data_table.setRowCount(len(nested_dict))
        self.data_table.setColumnCount(10)
        items = list(nested_dict.items())
        for i,j in items:
            if isinstance(j,dict):
                for row, (key,value) in enumerate(j.items()):
                    if isinstance(value,list):
                        key = str(key)
                        #value = str(value)
                        key_item = QTableWidgetItem(key)
                        value_item = QComboBox()
                        for dev in value:
                            str(dev)
                            value_item.addItem(dev)
                        self.data_table.setItem(i,2*row,key_item)
                        self.data_table.setCellWidget(i,2*row+1,value_item)
                    else:
                        key = str(key)
                        value = str(value)
                        key_item = QTableWidgetItem(key)
                        value_item = QTableWidgetItem(value)
                        self.data_table.setItem(i,2*row,key_item)
                        self.data_table.setItem(i,2*row+1,value_item)
                
        self.data_table.resizeColumnsToContents()  
    def setup_ui(self):
        self.main_layout = QVBoxLayout()
        self.header_label = self.setup_header()
        self.main_layout.addWidget(self.header_label)
        self.scroll_content = QWidget()
        self.scroll_layout = QGridLayout(self.scroll_content)
        self.scroll_area = QScrollArea()
        self.scroll_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.scroll_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.scroll_area.setWidgetResizable(True)
        self.scroll_area.setWidget(self.scroll_content)
        self.main_widget = QWidget()
        #self.main_widget.setStyleSheet("background-color: white;")
        self.side_widget = QWidget()
        #self.side_widget.setStyleSheet("background-color: white;")
        self.bottom_widget = QWidget()
        #self.bottom_widget.setStyleSheet("background-color: white;")
        self.scroll_layout.addWidget(self.main_widget,0,0,2,1)
        self.scroll_layout.addWidget(self.side_widget,0,1)
        self.scroll_layout.addWidget(self.bottom_widget,1,1)
        self.scroll_layout.setRowStretch(0,2)
        self.scroll_layout.setRowStretch(1,2)
        self.scroll_layout.setColumnStretch(0,2)
        self.scroll_layout.setColumnStretch(1,1)
        self.main_layout.addWidget(self.scroll_area)
        self.setLayout(self.main_layout)
    def setup_dropdown_info(self):

        self.side_widget_layout = QVBoxLayout()
        self.side_widget.setLayout(self.side_widget_layout)
        self.dropdown = QComboBox()
        self.dropdown.addItem('Average TMIT From BSA')
        self.dropdown.addItem('FW QSCL')
        self.dropdown.addItem('SW QSCL')
        self.dropdown.addItem('Wrong Size PIDs')
        self.dropdown.addItem('Dev Names of PIDs by Measurement')
        self.dropdown.addItem('Counts of BPMs per Unique PID')
        self.dropdown.currentIndexChanged.connect(self.load_data_table_signal)
        self.side_widget_layout.addWidget(self.dropdown)
        self.data_table = QTableWidget()
        self.data_table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)      
        self.side_widget_layout.addWidget(self.data_table)
        # self.side_widget.installEventFilter(self)
    def setup_control_grid(self):
        self.bottom_widget_layout = QGridLayout()
        self.bottom_widget.setLayout(self.bottom_widget_layout)
    
        self.ironing_ctrl_button = PyDMPushButton('Iron BPMs')
        self.ironing_ctrl_button.clicked.connect(self.ironing_button_signal)
        self.bottom_widget_layout.addWidget(self.ironing_ctrl_button)
    def setup_plot_grid(self):
        temp_num = int(self.class_macros['num'])
        self.plot_grid = PlotGrid(self.bsa_buffer.bpm_tmit_dictionary,self.bsa_buffer.bpm_tmit_averages_dictionary,temp_num)
        self.main_widget.setLayout(self.plot_grid)
    def setup_selector_grid(self):
        pass
    def setup_bsa_buffer(self):
        temp_num = int(self.class_macros['num'])
        temp_mask = ['SC_BSYD']
        self.bsa_buffer = BpmBSABuffer( temp_num,temp_mask,self.class_macros['mode'])
        self.bsa_buffer.start_buffer()
        self.bsa_buffer.get_tmit_buffers()
        self.pid_tool = PIDComparison(self.bsa_buffer.pulse_id_data,temp_num)
        self.wrong_size_pid = self.pid_tool.check_size(self.bsa_buffer.pulse_id_data,temp_num)
        print(self.wrong_size_pid)
        self.bpm_pid_counts_by_meas, self.bpm_pid_devs_by_meas = self.pid_tool.check_pulse_ids(self.bsa_buffer.pulse_id_data,temp_num)
        self.failures = self.pid_tool.get_total_dev_failures(self.wrong_size_pid,self.bpm_pid_devs_by_meas)
        self.bsa_buffer.release_buffer()   
    #plot_grid selector_grid and bsa_buffer must be before iron_bpms
    def iron_bpms(self):
        print(self.failures)
        self.ironing_tool = BpmIroningTool()
        self.bpm_tmits = self.ironing_tool.clean_signals(self.failures,self.bsa_buffer.bpm_tmit_averages_dictionary)
        self.bpm_fw_scls = self.ironing_tool.clean_signals(self.failures,self.plot_grid.fw_scl_pvs)
        self.bpm_sw_scls = self.ironing_tool.clean_signals(self.failures,self.plot_grid.sw_scl_pvs)
        #pprint.pprint(self.bpm_tmits)
        #pprint.pprint(self.bpm_fw_scls)
        #pprint.pprint(self.bpm_sw_scls)
        self.ratios = self.ironing_tool.get_scl_ratios(self.ref_bpm,self.bpm_tmits)
        #pprint.pprint(self.ratios)
        self.set_scl = self.ironing_tool.set_scl_ratios(self.bpm_fw_scls,self.ratios,':FW:QSCL')
        #pprint.pprint(self.set_scl)
    def ironing_button_signal(self):
        self.ironing_tool.put_pvs(self.set_scl)
        self.setup_bsa_buffer()
        self.plot_grid.update_ironed_plot(self.bsa_buffer.bpm_tmit_dictionary)
    '''
    def eventFilter(self,source,event):
        if source == self.side_widget and event.type() == QtCore.QEvent.Resize and self.app.applicationState() == QtCore.Qt.ApplicationActive:
            print(event)
            #self.updateSize(self.side_widget)
        if source == self.app and event.type() == QtCore.QEvent.ApplicationStateChange:
            print('state change')
            print(self.app.applicationState())
            if self.app.applicationState() == QtCore.Qt.ApplicationActive:
                print(type(self.app.applicationState()))
                
                print("GUI finished loading")
        return super().eventFilter(source,event)
    '''
class PlotGrid(QGridLayout):
    def __init__(self, y_data=None,y_ave_data = None,num_meas = None,*args, **kwargs):
        super().__init__(*args,**kwargs)

        #takes a dictionary of different signals and there y_data, uses keys to get z_pos pvs, and make x_data arrays
        
        self.tmit_vs_bsa_plot = pg.PlotWidget()
        self.ironed_tmit_plot = pg.PlotWidget()
        self.t1 = pg.PlotWidget()
        self.t2 = pg.PlotWidget()
        self.ave_tmit_vs_z_splot = pg.ScatterPlotItem()
        self.fw_scl_vs_z_splot = pg.ScatterPlotItem()
        self.t1.addItem(self.ave_tmit_vs_z_splot)
        self.t2.addItem(self.fw_scl_vs_z_splot)
        self.addWidget(self.tmit_vs_bsa_plot,0,0)
        self.addWidget(self.ironed_tmit_plot,0,1)
        self.addWidget(self.t1,1,0)
        self.addWidget(self.t2,1,1)
        self.num = num_meas
        self.tmit_dict = y_data
        self.tmit_ave_dict = y_ave_data

        self.y_data_keys = list(self.tmit_dict.keys())
        self.x_data = []
        #setting up x_data
        for i in range(self.num):
            self.x_data.append(i)
        
        self.get_pv_dicts()
        self.set_up_plots()


    def get_pv_dicts(self):

        # set up class attributes for plotting
        self.z_pos_pvs = {}
        self.fw_scl_pvs = {}
        self.sw_scl_pvs = {}
        #
        z_pos_pvs = []
        fw_scl_pvs = []
        sw_scl_pvs = []

        for key in self.y_data_keys:
            key = key.rsplit(':',1)[0]
            z_pos_pvs.append(key + ':Z')
            fw_scl_pvs.append(key +':FW:QSCL')
            sw_scl_pvs.append(key +':QSCL')

        got_z_pos = epics.caget_many(z_pos_pvs,timeout = 1)  
        got_fw_scl =  epics.caget_many(fw_scl_pvs,timeout = 1) 
        got_sw_scl =  epics.caget_many(sw_scl_pvs,timeout = 1) 

        for i in range(len(got_z_pos)):
            self.z_pos_pvs[z_pos_pvs[i]]=got_z_pos[i]
            self.fw_scl_pvs[fw_scl_pvs[i]]=got_fw_scl[i]
            self.sw_scl_pvs[sw_scl_pvs[i]]=got_sw_scl[i]

    def set_up_plots(self):
        for i in range(len(self.y_data_keys)):
            self.tmit_vs_bsa_plot.plot(self.x_data, self.tmit_dict[self.y_data_keys[i]], pen=(i,len(self.y_data_keys) ))
            self.ave_tmit_vs_z_splot.setData(list(self.z_pos_pvs.values()),list(self.tmit_ave_dict.values()))
            self.fw_scl_vs_z_splot.setData(list(self.z_pos_pvs.values()),list(self.fw_scl_pvs.values()))

        keys = list(self.tmit_ave_dict.keys())
        keys2 = list(self.z_pos_pvs.keys())
        keys3 = list(self.fw_scl_pvs.keys())

        for  i in range(len(keys)):
            print(self.tmit_ave_dict[keys[i]], ' ' , self.z_pos_pvs[keys2[i]], ' ', self.fw_scl_pvs[keys3[i]])
            print(keys[i],' ', keys2[i],' ', keys3[i])

    def update_ironed_plot(self,updated_tmit_dict):
        self.ironed_tmit_plot.clear()
        keys = list(updated_tmit_dict.keys())
        for i in range(len(keys)):
            self.ironed_tmit_plot.plot(self.x_data,updated_tmit_dict[keys[i]],pen=(i,len(keys)))     
class BpmBSABuffer():
    def __init__(self,num_measurements,dest_masks,dest_mode,*args,**kwargs):
        self.bpm_bsa_buffer = BSABuffer('Chris BPM Testing', user= 'cgarnier')
        self.buffer_num = self.bpm_bsa_buffer.number
        print(self.buffer_num)
        self.bpm_bsa_buffer.destination_masks = dest_masks
        self.bpm_bsa_buffer.n_measurements = num_measurements
        self.put_pv = 'BSA:SYS0:1:'+str(self.buffer_num)+':DESTMODE'
        self.put = epics.caput(self.put_pv,dest_mode)

    def start_buffer(self):
        self.bpm_bsa_buffer.start()
        while not self.bpm_bsa_buffer.is_acquisition_complete():
            time.sleep(0.1)

    def release_buffer(self):
        self.bpm_bsa_buffer.release()

    def get_tmit_buffers(self):

        # set up class attributes
        self.bpm_tmit_dictionary = {}
        self.bpm_tmit_averages_dictionary = {}
        self.active_bpm_tmit_pvs = []
        self.pulse_id_data = {}
        #

        bpm_tmit_pvs = []
        # get a list of connected bpms
        for bpm in sc_bpm_list:
            bpm_tmit_pvs.append(bpm+':TMIT')

        got_list=epics.caget_many(bpm_tmit_pvs)

        for i in range(len(got_list)):
            if got_list[i] is not None:
                self.active_bpm_tmit_pvs.append(bpm_tmit_pvs[i])
        # get tmit data buffer, take the average, and store both in class attributes
        # also store the PID info in class attributes
        for i in range(len(self.active_bpm_tmit_pvs)):
            temp = self.bpm_bsa_buffer.get_data_buffer(self.active_bpm_tmit_pvs[i])
            ### sometimes taking mean of empty obj
            ave = np.mean(temp)
            self.bpm_tmit_dictionary[self.active_bpm_tmit_pvs[i]] = temp 
            self.bpm_tmit_averages_dictionary[self.active_bpm_tmit_pvs[i]] = ave
           
            self.pulse_id_data[self.active_bpm_tmit_pvs[i]] = epics.caget(self.active_bpm_tmit_pvs[i]+'PIDHST'+str(self.buffer_num),timeout = 1.5)
class PIDComparison():
    ### meant to get perform all PID tasks, returns a list of signals that fail PID tests
    def __init__(self, pid_dictionary,num_measurements):
        self.pid_dictionary = pid_dictionary
        self.num_measurements = num_measurements
    def find_failures(self):

        #
        self.failures = 0
        self.failures_list = []
        self.failing_devices = []
        self.wrong_size_pid = {}
        self.pid_bpm_counts = {}
        #
        pulse_key_list = list(self.pid_dictionary.keys())

        for key in range(len(pulse_key_list)):
            if len(self.pid_dictionary[key]) != self.num_measurements:
                self.wrong_size_pid[key] = len(self.pid_dictionary[key])
                print(key, ' does not match the measurement num')

        
        for i in self.num_measurements:
            temp = {}
            for j in range(len(pulse_key_list)):
                if self.pid_dictionary[pulse_key_list[j]][i] in temp.keys():
                    temp[self.pid_dictionary[pulse_key_list[j]][i]] +=1
                else:
                    temp[self.pid_dictionary[pulse_key_list[j]][i]] =1
                    print(pulse_key_list[j])
    @staticmethod
    def check_size(pulse_id_dict,num_measurements):
        wrong_size_pid = {}
        pulse_key_list = list(pulse_id_dict.keys())
        for key in pulse_key_list:
           if len(pulse_id_dict[key]) != num_measurements:
               wrong_size_pid[key] = len(pulse_id_dict[key])
        return wrong_size_pid  
    @staticmethod
    def check_pulse_ids(pulse_id_dict,num_measurements):
        ###write some logic here to make sure no undersizes - happens for DIAG0
        pulse_key_list = list(pulse_id_dict.keys())

        bpm_counts_per_pid = {}
        failed_match_dictionary = {}
        
        for i in range(num_measurements):
            temp_counts = {}
            temp_bpms = {}
            
            for j in range(len(pulse_key_list)):
                temp_array = []
                if pulse_id_dict[pulse_key_list[j]][i] in temp_counts.keys():
                    temp_counts[pulse_id_dict[pulse_key_list[j]][i]] +=1
                    temp_bpms[pulse_id_dict[pulse_key_list[j]][i]].append(pulse_key_list[j])

                else:
                    temp_counts[pulse_id_dict[pulse_key_list[j]][i]] =1  
                    temp_bpms[pulse_id_dict[pulse_key_list[j]][i]] = temp_array
                    temp_bpms[pulse_id_dict[pulse_key_list[j]][i]].append(pulse_key_list[j])
               
            bpm_counts_per_pid[i] = temp_counts
            failed_match_dictionary[i] = temp_bpms

        return bpm_counts_per_pid,failed_match_dictionary    
    @staticmethod 
    def get_total_dev_failures(wrong_pid_dict,dev_vs_pid_dict):
        temp1 = []
        temp_keys = []
        d_list = []
        totals = []
        for key in wrong_pid_dict.keys():
            temp1.append(key)
        #print(dev_vs_pid_dict)
        nest_list = list(dev_vs_pid_dict.items())
        for i,j in nest_list:
            if isinstance(j,dict):
                k = j.copy()
                big_len = 0
                pop_key = None
                keys = list(k.keys())
                
                #print('len of keys is: ', len(keys))
                if len(keys) > 1:
                    for key in keys:
                        #print(key)
                        temp_len = len(k[key])
                        if temp_len> big_len:
                            pop_key = key
                            big_len = temp_len
                        else:
                            continue

                if pop_key is not None:
                    temp_keys.append(pop_key)
                    k.pop(pop_key)
                    for value in k.values():
                        if isinstance(value,list):
                            for val in value:
                                d_list.append(val)
                        else:
                            d_list.append(value)
        
        #print(d_list)

        temp = temp1 + d_list
        for dev in temp:
            if dev not in totals:
                totals.append(dev)
        print(totals)
        return totals
class BpmIroningTool():
    def __init__(self):
        print('Instantiating tool that has methods useful for ironing')

    @staticmethod
    def clean_signals(pop_list,dict_to_pop):
        copy_dict = dict_to_pop.copy()
        keys = list(copy_dict.keys())
        for kpop in pop_list:
            for key in keys:
                if kpop in key:
                    #eg pop  = 'BPMS:L1B:0283' and key = 'BPMS:L1B:0283:TMIT'
                    copy_dict.pop(key)
        return copy_dict
    
    @staticmethod
    def get_scl_ratios(ref_bpm,set_scl_dict):
        ref_val = float('nan')
        ratios = {}
        for key in list(set_scl_dict.keys()):
            if ref_bpm in key:
                ref_val = set_scl_dict[key]
                break
        for key in list(set_scl_dict.keys()):
            if math.isnan(set_scl_dict[key]) or math.isnan(ref_val):
                pass
            else:
                temp_key = key.rsplit(':',1)[0]
                ratios[temp_key] = set_scl_dict[key]/ref_val
        ###add check that ref bpm ratio is 1.0
        
        return ratios
    
    @staticmethod
    def set_scl_ratios(set_scl_dict,get_scl_dict,scl_ext):
        scl_dict = {}
        for key in list(get_scl_dict.keys()):
            scl_key = key + scl_ext
            scl_dict[scl_key] = set_scl_dict[scl_key] * get_scl_dict[key]
        return scl_dict
    
    @staticmethod
    def put_pvs(set_scl_dict):
        print('set')

