from qtpy import QtCore, QtGui
from qtpy.QtWidgets import (QFrame, QLabel, QHBoxLayout,
                            QVBoxLayout, QLineEdit, QFileDialog,
                            QPushButton, QTabWidget, QTableWidget,
                            QWidget, QSpacerItem,QSizePolicy, 
                            QLineEdit, QHeaderView)
from pydm import Display
from pydm.widgets import PyDMLabel
from pydm.widgets.drawing import PyDMDrawingCircle
from pydm.widgets.scatterplot import (PyDMScatterPlot,
                                      ScatterPlotCurveItem)
from pydm.widgets.archiver_time_plot import (PyDMArchiverTimePlot,
                                             ArchivePlotCurveItem)
from functools import partial
import superprobe_pvfields
import epics

import pandas as pd
import numpy as np

import argparse

class MainWindow(Display):

    def __init__(self, parent=None, macros=None, args=None):
        super(MainWindow, self).__init__(args=args, 
                                         parent=parent,
                                         macros=macros)

        self.setWindowTitle('SuperProbe')

        self.main_layout = QVBoxLayout()
        self.setLayout(self.main_layout)

        self.setMinimumSize(750,750)

        arg_parser = argparse.ArgumentParser()

        ## Add Primary PV argument
        arg_parser.add_argument('--pv',
                                help = 'Primary PV to display.',
                                type = str)

        self.args = arg_parser.parse_args(args)

        self.create_ui()
        self.handle_arguments(self.data_frame)

## Create main data frame that holds important widgets for the UI
## Allows one variable (the data frame) to contain most information
    def create_data_frame(self):
        ## Data frame columns are main UI elements
        columns = ['Main Window', 'Time Plot', 'Correlation Plot',
                   'Fields Table']

        ## Data frame rows are the functional widgets
        index = ['Primary PV', 'Primary RBV', 'Secondary PV',
                 'Secondary RBV', 'Main Widget', 'Reset Button',
                 'Clear Button', 'Clear Function', 'Snapshot Button',
                 'Filter Term']

        ## Instantiate the data frame
        df = pd.DataFrame(columns = columns, index = index)

        ## Main Window PV entries
        df['Main Window']['Primary PV'] = QLineEdit()
        df['Main Window']['Secondary PV'] = QLineEdit()
        df['Main Window']['Secondary PV'].setEnabled(False)

        ## Time Plot main widget
        tp_mw = PyDMArchiverTimePlot(background=[255,255,255,255])
        df['Time Plot']['Main Widget'] = tp_mw

        ## Correlation Plot main wideget
        cp_mw = PyDMScatterPlot(background=[255,255,255,255])
        df['Correlation Plot']['Main Widget'] = cp_mw

        ## Fields Table main widget and filter entry
        df['Fields Table']['Main Widget'] = QTableWidget()
        df['Fields Table']['Filter Term'] = QLineEdit()
        df['Fields Table']['Filter Term'].setEnabled(False)
        df['Fields Table']['Filter Term'].setPlaceholderText('Enter search term here...')

        ## Many widgets are duplicated across each main UI element
        for column in ['Time Plot', 'Correlation Plot',
                       'Fields Table']:

            ## PV Readbacks
            pri_rbv = PyDMLabel()
            pri_rbv.setMinimumWidth(60)
            df[column]['Primary RBV'] = pri_rbv

            sec_rbv = PyDMLabel()
            sec_rbv.setMinimumWidth(60)
            df[column]['Secondary RBV'] = sec_rbv

            ## Make the 'Reset All' button
            rb = QPushButton('Reset All')
            rb.setEnabled(False)
            rb.clicked.connect(partial(self.reset_all, df))
            df[column]['Reset Button'] = rb

            ## Make the 'Clear' button
            cb = QPushButton('Clear')
            cb.setEnabled(False)
            cb.clicked.connect(partial(self.clear, df, column))
            df[column]['Clear Button'] = cb

            ## Make the 'Snapshot' button
            df[column]['Snapshot Button'] = QPushButton('Snapshot')
            df[column]['Snapshot Button'].setEnabled(False)

        return df

    ## Function to create the tab container with all three base tabs
    def create_tab_widget(self, data_frame):
        ## Instantiate base widget
        tab_container = QTabWidget()

        ## The three tab base widgets
        time_plot_tab = QWidget()
        time_plot_tab.setStyleSheet('.QWidget{background-color:rgb(218,218,218)}')
        correlation_plot_tab = QWidget()
        correlation_plot_tab.setStyleSheet('.QWidget{background-color:rgb(218,218,218)}')
        pv_fields_tab = QWidget()

        tabs = [time_plot_tab, correlation_plot_tab, pv_fields_tab]

        ## Get titles from columns of the data frame
        columns = list(data_frame.columns)
        tab_titles = columns[1:4]

        ## Add the tab to the container, set the name of the tab,
        ## and create the graphical elements for each tab
        for i in range(len(tabs)):
            tab_container.addTab(tabs[i], tab_titles[i])

        ## Create the Time Plot UI
        self.create_plot_tab(time_plot_tab, data_frame, 'Time Plot')
        ## Create the Correlation Plot UI
        self.create_plot_tab(correlation_plot_tab, data_frame, 
                             'Correlation Plot')
        ## Create the Fields Table UI
        self.create_fields_tab(pv_fields_tab, data_frame, 'Fields Table')

        return tab_container

    def create_plot_tab(self, tab, data_frame, df_column):
        ## Set tab layout
        layout = QVBoxLayout()
        tab.setLayout(layout)

        ## Create the PV frame to hold Primary and Secondary PV info
        pv_frame = self.create_tab_pv_frame(data_frame, df_column)
        ## Create the Main Widget Frame to hold the Plot widget
        main_widget_frame = self.create_main_widget_frame(data_frame,
                                                              df_column)
        ## Create the Buttons Frame to hold action buttons
        buttons_frame = self.create_buttons_frame(data_frame,
                                                      df_column)

        ## Create list of Frames for Plot Tabs 
        frames = [pv_frame, main_widget_frame,
                  buttons_frame]

        ## Add all frames to main tab
        for frame in frames:
            layout.addWidget(frame)

    def create_fields_tab(self, tab, data_frame, df_column):
        ## Set tab layout
        layout = QVBoxLayout()
        tab.setLayout(layout)

        ## Create the PV Frame to hold Primary PV info
        pv_frame = self.create_tab_pv_frame(data_frame, df_column)
        pv_frame.setMinimumHeight(50)
        ## Create the Main Widget Frame to hold the Table widget
        main_widget_frame = self.create_main_widget_frame(data_frame, 
                                                              df_column)
        ## Create the Buttons Frame to hold action buttons
        buttons_frame = self.create_buttons_frame(data_frame,
                                                      df_column)
       
        ## Create a Frame to hold the widgets related to Filtering
        filter_frame = QFrame()
        filter_layout = QHBoxLayout()
        filter_frame.setLayout(filter_layout)
        filter_frame.setMaximumHeight(50)

        ## Create or call the Widgets related to Filtering
        filter_lbl = QLabel('Filter:')
        filter_edit = data_frame[df_column]['Filter Term']
        filter_edit.returnPressed.connect(partial(self.do_search_action,
                                                  data_frame))

        filter_spacer = QSpacerItem(20, 10, QSizePolicy.Expanding,
                              QSizePolicy.Expanding)

        search_btn = QPushButton('Search')
        search_btn.clicked.connect(partial(self.do_search_action, 
                                           data_frame))

        reset_btn = QPushButton('Reset Search')
        reset_btn.clicked.connect(partial(self.reset_search, data_frame))

        ## Add Filter Widgets to Filter Frame
        for widget in [filter_lbl, filter_edit, filter_spacer,
                       search_btn, reset_btn]:
            try:
                filter_layout.addWidget(widget)
            except:
                filter_layout.addItem(filter_spacer)

        ## Create Info Frame that holds a label with info
        ## about what the frame is showing 
        info_frame = QFrame()
        info_layout = QHBoxLayout()
        info_frame.setLayout(info_layout)

        ## Create Label that says what the 'Fields Table' is
        info_lbl = QLabel('PV fields associated with Primary PV')
        info_layout.addWidget(info_lbl)

        ## Create list of Frames for Fields Table
        frames = [pv_frame, filter_frame,
                  main_widget_frame, info_frame,
                  buttons_frame]

        ## Add all frames to main tab
        for frame in frames:
            layout.addWidget(frame)

    def create_tab_pv_frame(self, data_frame, df_column):
        ## PV info frame
        frame = QFrame()
        frame.setStyleSheet('PyDMLabel {background: rgb(255,255,255);\n'
                           'color: rgb(0, 32, 88);\n'
                           'padding: 4px;}')
        layout = QVBoxLayout()
        frame.setLayout(layout)
        frame.setMaximumHeight(100)

        ## Create Primary PV frame
        pri_frame = QFrame()
        pri_layout = QHBoxLayout()
        pri_frame.setLayout(pri_layout)
        pri_frame.setMinimumHeight(40)

        ## Create or call the widgets to add to the Primary PV frame 
        pri_lbl = QLabel('Primary PV Value:')
        pri_rbv = data_frame[df_column]['Primary RBV']
        pri_rbv.setText('')

        pri_spacer = QSpacerItem(20, 10, QSizePolicy.Expanding,
                              QSizePolicy.Expanding)
        
        ## Add the widgets to the Primary PV Frame
        for widget in [pri_lbl, pri_rbv]:
            pri_layout.addWidget(widget)
        pri_layout.addItem(pri_spacer)

        ## Create Secondary PV Frame
        sec_frame = QFrame()
        sec_layout = QHBoxLayout()
        sec_frame.setLayout(sec_layout)
        sec_frame.setMinimumHeight(40)

        ## Create or call the widgets to add to the Secondary PV Frame
        sec_lbl = QLabel('Secondary PV Value:')
        sec_rbv = data_frame[df_column]['Secondary RBV']
        sec_rbv.setText('')

        sec_spacer = QSpacerItem(20, 10, QSizePolicy.Expanding,
                                 QSizePolicy.Expanding)

        ## Add the widgets to the Secondary PV Frame
        for widget in [sec_lbl, sec_rbv]:
            sec_layout.addWidget(widget)
        sec_layout.addItem(sec_spacer)

        for widget in [pri_frame, sec_frame]:
            layout.addWidget(widget)

        if df_column == 'Fields Table':
            sec_frame.hide()
            frame.setMaximumHeight(50)

        return frame

    def create_main_widget_frame(self, data_frame, df_column):
        ## Create Plot Frame and add Plot
        frame = QFrame()
        layout = QHBoxLayout()
        frame.setLayout(layout)

        widget = data_frame[df_column]['Main Widget']
        layout.addWidget(widget)

        ## Set Time Plot widget timespan to 60 seconds
        if df_column == 'Time Plot':
            widget.setTimeSpan(60)
        elif df_column == 'Fields Table':
            fields = superprobe_pvfields.fields
            widget.setColumnCount(3)
            widget.setRowCount(len(fields['all']))

            headers = ['Field', 'Summary', 'Readback']
            widget.setHorizontalHeaderLabels(headers)

            widget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        layout.addWidget(widget)

        return frame

    def create_buttons_frame(self, data_frame, df_column):
        ## Create buttons frame and add buttons
        frame = QFrame()
        layout = QHBoxLayout()
        frame.setLayout(layout)
        frame.setMaximumHeight(50)

        reset_btn = data_frame[df_column]['Reset Button']

        clear_btn = data_frame[df_column]['Clear Button']
        
        btn_spacer = QSpacerItem(20, 10, QSizePolicy.Expanding,
                              QSizePolicy.Expanding)

        ## Create list of widgets to add to Button Frame
        widgets = [reset_btn, clear_btn, btn_spacer]

        ## Create Snapshot Button for Plot tabs
        if df_column != 'Fields Table':
            snap_btn = data_frame[df_column]['Snapshot Button']
            snap_btn.clicked.connect(partial(self.plot_snapshot, data_frame,
                                             df_column))
            
            ## Append Snapshot Button to list
            widgets.append(snap_btn)

        ## Add widgets to Button Frame
        for widget in widgets:
            try:
                layout.addWidget(widget)
            except:
                layout.addItem(widget)

        return frame

    ## Function to reset the display to default (launch)
    def reset_all(self, data_frame):
        ## Get the PV entry widgets
        pri_edit = data_frame['Main Window']['Primary PV']
        sec_edit = data_frame['Main Window']['Secondary PV']

        ## Remove any text
        pri_edit.setText('')
        sec_edit.setText('')

        ## Reset the individual tabs
        self.reset_time_plot(data_frame)
        self.reset_corr_plot(data_frame)
        self.reset_fields_table(data_frame)

    ## Function to reset Time Plot
    def reset_time_plot(self, data_frame):
        ## Get the readback widgets
        pri_rbv = data_frame['Time Plot']['Primary RBV']
        sec_rbv = data_frame['Time Plot']['Secondary RBV']

        self.erase_time_plot(data_frame)

        ## Remove any readback information
        pri_rbv.setText('')
        pri_rbv.channel = ''

        sec_rbv.setText('')
        sec_rbv.channel = ''

    ## Function to reset Correlation Plot
    def reset_corr_plot(self, data_frame):
        ## Get the readback widgets
        pri_rbv = data_frame['Correlation Plot']['Primary RBV']
        sec_rbv = data_frame['Correlation Plot']['Secondary RBV']

        self.clear_corr_plot(data_frame)

        ## Remove any readback information
        pri_rbv.setText('')
        pri_rbv.channel = ''

        sec_rbv.setText('')
        sec_rbv.channel = ''

    def reset_fields_table(self, data_frame):
        ## Get readback widgets
        table = data_frame['Fields Table']['Main Widget']
        pri_rbv = data_frame['Fields Table']['Primary RBV']

        ## Get table information
        row_count = table.rowCount()
        column_count = table.columnCount()

        ## Set text empty for all table cells
        try:
            for i in range(row_count):
                for j in range(column_count):
                    table.cellWidget(i, j).setText('')
        except:
            ## Skip any already empty cells
            pass

        ## Remove any readback information
        pri_rbv.setText('')
        pri_rbv.channel = ''

    ## Function to save plot as a .PNG file
    def plot_snapshot(self, data_frame, df_column):
        ## Get plot widget
        plot = data_frame[df_column]['Main Widget']

        ## Grab image
        p = plot.grab()

        ## Instantiate dialog to get file name
        file_dialog = QFileDialog()
        file_dialog.setDefaultSuffix('.png')

        ## Note that the file dialog returns a list and we want element [0]
        snap_file = file_dialog.getSaveFileName(self, 'Save Snapshot', '',
                                                'Portable Network Graphics (*.png)')[0]

        ## If file name captured (e.g., dialog not cancelled) save file        
        if snap_file:
            p.save(snap_file + '.png', 'png')

    ## General function to select a particular clearing function
    def clear(self, data_frame, column):
        if column == 'Time Plot':
            self.clear_time_plot(data_frame)
        elif column == 'Correlation Plot':
            self.clear_corr_plot(data_frame)
        elif column == 'Fields Table':
            self.reset_fields_table(data_frame)

    ## Remove Time Plot channels
    def erase_time_plot(self, data_frame):
        ## Get Time Plot widget
        plot = data_frame['Time Plot']['Main Widget']

        ## Will remove both channels if Primary and Secondary are plotted
        for i in range(2):
            try:
                plot.removeAxisAtIndex(0)
                plot.clearCurves()
            except:
                pass

    ## Remove data from the Time Plot display and re-add the channels
    ## to start the plot over
    def clear_time_plot(self, data_frame):
        ## Remove channels first
        self.erase_time_plot(data_frame)

        ## Get PV names
        pri_pv = data_frame['Main Window']['Primary PV'].text()
        sec_pv = data_frame['Main Window']['Secondary PV'].text()

        ## Add Primary PV to plot
        self.add_time_plot_channel(data_frame, pri_pv, pri_pv,
                                   'blue', 'Axis 1')
        ## If Secondary PV exists, add it to plot as well
        if sec_pv != '':
            self.add_time_plot_channel(data_frame, sec_pv, sec_pv,
                                       'red', 'Axis 2')

    ## Remove data from Correlation Plot display and re-add the channels
    ## to start the plot over
    def clear_corr_plot(self, data_frame):
        ## Get the Correlation Plot widget
        plot = data_frame['Correlation Plot']['Main Widget']

        ## Remove the curve items
        plot.clearCurves()

        ## Try except loop handles startup when there is no axis
        try:
            ## Clear all titles
            plot.setLabels(title='',
                           left='',
                           bottom='')
            ## Remove axis
            plot.removeAxisAtIndex(0)
        except:
            pass

        ## Get PV names
        pri_pv = data_frame['Main Window']['Primary PV'].text()
        sec_pv = data_frame['Main Window']['Secondary PV'].text()

        ## No PVs entered
        if pri_pv == '':
            ## Set titles empty
            plot.setLabels(title = '',
                           left = '',
                           bottom = '')
        ## Primary vs Primary
        elif sec_pv == '':
            self.add_corr_plot_channel(data_frame, pri_pv, 
                                       pri_pv, 'blue',
                                       'o', 2)
            ## Reset the titles
            plot.setLabels(title = pri_pv + ' vs. ' + pri_pv,
                           left = pri_pv,
                           bottom = pri_pv)

        ## Primary vs Secondary
        elif sec_pv != '':
            self.add_corr_plot_channel(data_frame, pri_pv, 
                                       sec_pv, 'blue',
                                       'o', 2)
            ## Reset the titles  
            plot.setLabels(title = pri_pv + ' vs. ' + sec_pv,
                           left = pri_pv,
                           bottom = sec_pv)  



    ## Function that filters Fields Table display based on input
    def do_search_action(self, data_frame):
        ## Get filter term from line edit
        filter_term = data_frame['Fields Table']['Filter Term'].text()
        table = data_frame['Fields Table']['Main Widget']
        row_count = table.rowCount()

        ## If filter term exists, filter the table
        if filter_term != '':
            for i in range(row_count):
                ## Hide all rows to begin
                table.hideRow(i)
                ## Get the text for each of cell in arow
                field_text = table.cellWidget(i, 0).text()
                summary_text = table.cellWidget(i, 1).text()
                readback_text = table.cellWidget(i, 2).text()

                ## If filter text appears in any of these cells, 
                ## show the whole row
                for text in [field_text, summary_text, readback_text]:
                    if filter_term.lower() in text.lower():
                        table.showRow(i)  

    ## Function to reset the search info
    def reset_search(self, data_frame):
        ## Get the relevant widgets
        filter_term = data_frame['Fields Table']['Filter Term']
        table = data_frame['Fields Table']['Main Widget']

        ## Set the entry text empty
        filter_term.setText('')

        ## Show every row in the table
        for i in range(table.rowCount()):
            table.showRow(i)

    def create_pv_frame(self, data_frame):
        ## Main Frame
        main_frame = QFrame()
        main_frame.setStyleSheet('QFrame{background-color: rgb(218,218,218)}\n'
                                 'QLineEdit{background-color:rgb(240,240,240)}')
        main_layout = QVBoxLayout()
        main_frame.setLayout(main_layout)

        ## Primary PV Frame
        pri_frame = QFrame()
        pri_layout = QHBoxLayout()
        pri_frame.setLayout(pri_layout)

        pri_lbl = QLabel('Primary PV:')
        pri_edit = data_frame['Main Window']['Primary PV']
        pri_edit.setPlaceholderText('Enter PV here...')

        ## Connect the widget with the function that sends the PV
        pri_edit.returnPressed.connect(partial(self.pass_pv, data_frame, 
                                               'Primary'))
        ## Add widgets to Primary PV Frame
        for widget in [pri_lbl, pri_edit]:
            pri_layout.addWidget(widget)

        ## Secondary PV Frame
        sec_frame = QFrame()
        sec_layout = QHBoxLayout()
        sec_frame.setLayout(sec_layout)

        sec_lbl = QLabel('Secondary PV:')
        sec_edit = data_frame['Main Window']['Secondary PV']
        sec_edit.setPlaceholderText('Enter PV here...')

        ## Connect the widget with the function that sends the PV
        sec_edit.returnPressed.connect(partial(self.pass_pv, data_frame, 
                                              'Secondary'))
        
        ## Add widgets to Primary PV Frame
        for widget in [sec_lbl, sec_edit]:
            sec_layout.addWidget(widget)

        ## Add PV Frames to the Main Frame
        for frame in [pri_frame, sec_frame]:
            main_layout.addWidget(frame)

        return main_frame

    ## Function that makes everything happen
    ## Takes PV from line edit widgets and passes it to plots, readbacks, and table
    def pass_pv(self, data_frame, index):
        ## Index is 'Primary' or 'Secondary' to pick proper widget from Data Frame
        ## Get the text from the appropriate Line Edit
        pv = data_frame['Main Window'][index + ' PV'].text()

        ## Get Correlation Plot for setting titles
        corr_plot = data_frame['Correlation Plot']['Main Widget']

        ## Get Readback widgets
        time_rbv = data_frame['Time Plot'][index + ' RBV']
        corr_rbv = data_frame['Correlation Plot'][index + ' RBV']
        pv_fields_rbv = data_frame['Fields Table'][index + ' RBV'] 

        ## Only run the main chunk of the function if the PV is not empty
        if pv != '':
            if index == 'Primary':
                ## Clear any plots so not to scramble the plot with many lines
                self.clear_time_plot(data_frame)
                self.clear_corr_plot(data_frame)

                ## Add the PVs to the plots
                self.add_time_plot_channel(data_frame, pv, pv, 'blue',
                                           'Axis 1')
                self.add_corr_plot_channel(data_frame, pv, pv, 'blue',
                                           'o', 2)

                ## Set the titles of the Correlation Plot
                corr_title = pv + ' vs. ' + pv
                corr_plot.setLabels(title=corr_title,
                                    left=pv,
                                    bottom=pv)

                ## Get a list of the readback PVs and set the channel
                pri_rbvs = [time_rbv, corr_rbv, pv_fields_rbv]
                for rbv in pri_rbvs:
                    rbv.channel = pv

                ## Apply the PV to the Fields Table
                self.fill_table(pv, data_frame)
                ## Enable the Secondary Widget line edit and 
                ## the 'Reset All', 'Clear', and 'Snapshot' buttons
                self.enable_widgets(data_frame)

            elif index == 'Secondary':
                ## Add to Time Plot as 'Axis 2'
                self.add_time_plot_channel(data_frame, pv, pv, 'red',
                                           'Axis 2')

                ## Clear the Correlation Plot in preparation for 
                ## adding more PVs 
                self.clear_corr_plot(data_frame)

                ## Since PV that initiated this loop is 'Secondary',
                ## get the 'Primary' PV
                pri_pv = data_frame['Main Window']['Primary PV'].text()

                ## Add both PVs to the Correlation Plot
                self.add_corr_plot_channel(data_frame, pri_pv, pv,
                                           'blue', 'o', 2)

                corr_plot.setLabels(title = pri_pv + ' vs. ' + pv,
                                    left = pri_pv,
                                    bottom = pv)

                sec_rbvs = [time_rbv, corr_rbv]
                for rbv in sec_rbvs:
                    rbv.channel = pv

    def enable_widgets(self, data_frame):
        for tab in ['Time Plot', 'Correlation Plot', 
                    'Fields Table']:
            data_frame[tab]['Reset Button'].setEnabled(True)
            data_frame[tab]['Clear Button'].setEnabled(True)
            data_frame[tab]['Snapshot Button'].setEnabled(True)
                
        data_frame['Main Window']['Secondary PV'].setEnabled(True)
        data_frame['Fields Table']['Filter Term'].setEnabled(True)

    def add_time_plot_channel(self, df, y_channel, name,
                              color, yAxisName):

        plot = df['Time Plot']['Main Widget']
        plot.addYChannel(y_channel=y_channel,
                         name = name,
                         color = color,
                         yAxisName = yAxisName,
                         useArchiveData = True)

    def add_corr_plot_channel(self, df, y_channel, x_channel, 
                              color, symbol, lineWidth):

        plot = df['Correlation Plot']['Main Widget']
        plot.addChannel(y_channel=y_channel,
                        x_channel = x_channel,
                        color = color,
                        symbol = symbol,
                        lineWidth = lineWidth)

    def fill_table(self, pv, data_frame):
        table = data_frame['Fields Table']['Main Widget']
        
        rtyp = epics.caget(pv + '.RTYP')
        fields = superprobe_pvfields.fields

        fields_all = fields['all']
        all_keys = list(fields_all.keys())

        fields_rtyp = fields[rtyp]
        rtyp_keys = list(fields_rtyp.keys())

        fields_combined = {**fields_all, **fields_rtyp}
        combined_keys = list(fields_combined.keys())

        num_keys = len(combined_keys)
        table.setRowCount(num_keys)

        table_dict = {}
        for i in range(num_keys):
            table_dict[str(i)] = {}
            sub_dict = table_dict[str(i)]

            field = str(fields_combined[combined_keys[i]])
            sub_dict['Field'] = QLabel(field)

            summary = str(combined_keys[i])
            sub_dict['Summary'] = QLabel(summary)

            readback_str = pv + '.' + str(sub_dict['Field'].text())
            sub_dict['Readback'] = PyDMLabel()
            sub_dict['Readback'].channel = readback_str

        for i in range(num_keys):
            row_dict = table_dict[str(i)]
            field_widget = row_dict['Field']
            summary_widget = row_dict['Summary']
            readback_widget = row_dict['Readback']

            table.setCellWidget(i, 0, field_widget)
            table.setCellWidget(i, 1, summary_widget)
            table.setCellWidget(i, 2, readback_widget)

    ## Function to create the header frame that holds the title and other info
    def create_header_frame(self):
        ## Make the header frame and set the layout
        frame = QFrame()
        frame.setStyleSheet('background-color: rgb(230,230,230);\n'
                            'color: rgb(79,79,79)')
        frame.setFixedHeight(45)
        #frame.setContentsMargins(10,4,0,4)
        layout = QHBoxLayout()
        frame.setLayout(layout)

        ## Make the 'LCLS' label on the left margin
        lcls = QLabel("LCLS")
        lcls.setStyleSheet("QLabel{background: transparent;\n"
                           "color: rgb(140, 21, 21);\n"
                           "font-weight: bold;\n"
                           "font-size: 29px;}")

        ## Make the smaller label on the left margin
        apps = QLabel("GLOBAL\n"
                      "APPLICATIONS")
        apps.setStyleSheet("QLabel{background: transparent;\n"
                           "color: rgb(79, 79, 79);\n"
                           "font-size: 11px;}")
        apps.wordWrap = True

        ## Make the title of the main page
        title = QLabel("SuperProbe")
        title.setStyleSheet("QLabel{background: transparent;\n"
                            "color: rgb(55, 55, 55);\n"
                            "font-size: 24px;\n"
                            "font-weight: bold;}")

        ## Need to make a second frame for the right margin
        detail_frame = QFrame()
        detail_layout = QVBoxLayout()
        detail_frame.setLayout(detail_layout)

        detail_layout.setContentsMargins(0, 0, 0, 0)

        ## Current time and date display
        clock = PyDMLabel()
        clock.channel = "SIOC:SYS0:AL00:TOD"

        ## Displays the current network, Production or Development
        network = PyDMLabel()
        network.channel = "SIOC:SYS0:AL00:MODE"

        ## Add the widgets to the right margin frame
        for widget in [clock, network]:
            detail_layout.addWidget(widget)

        ## Make two spacers to help center the title label
        spacer1 = QSpacerItem(20, 10, QSizePolicy.Expanding,
                              QSizePolicy.Expanding)
        spacer2 = QSpacerItem(20, 10, QSizePolicy.Expanding,
                              QSizePolicy.Expanding)

        ## Add all widgets to the header frame
        for widget in [lcls, apps, spacer1, title,
                       spacer2, detail_frame]:
            try:
                layout.addWidget(widget)
            except:
                layout.addItem(widget)

        frame.setMaximumHeight(60)

        return frame

    def create_ui(self):
        self.data_frame = self.create_data_frame()
        header_frame = self.create_header_frame()
        pv_frame = self.create_pv_frame(self.data_frame)
        tab_widget = self.create_tab_widget(self.data_frame)

        for widget in [header_frame, pv_frame, tab_widget]:
            self.main_layout.addWidget(widget)

    def handle_arguments(self, data_frame):
        ## Get PV argument
        pv = self.args.pv
        
        if pv:
            data_frame['Main Window']['Primary PV'].setText(pv)
            self.pass_pv(data_frame, 'Primary')
