from qtpy.QtWidgets import (QHBoxLayout, QVBoxLayout,
                            QGridLayout, QLabel, QPushButton, 
                            QFrame, QTableWidget, QLineEdit,
                            QSpacerItem, QSizePolicy, QFileDialog,
                            QHeaderView)
from PyQt5 import QtCore
from pydm import Display
from pydm.widgets import PyDMLabel, PyDMLineEdit
from pydm.widgets.display_format import DisplayFormat
from pydm.widgets.channel import PyDMChannel
from functools import partial
import epics
import pandas as pd
import os

ROW_COUNT = 1000
SORT_ORDER = [False, False, False, 
                  False, False, False, 
                  False, False, False, False]

class MainWindow(Display):
    def __init__(self, *args, **kwargs):       
        super(MainWindow, self).__init__(*args, **kwargs)

        ## Set main layout to Vertical Box
        self.main_layout = QVBoxLayout()
        self.setLayout(self.main_layout)

        self.setWindowTitle('PV Table')
        self.setMinimumSize(1155,527)

        ## Create the UI and run all the functions
        self.create_UI(ROW_COUNT)

## Function to instantiate table widget
    def create_table(self, row_count, dictionary):
        ## Instantiate table widget
        table = QTableWidget()
        table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        table.horizontalHeader().setSectionsClickable(True)
        table.horizontalHeader().setSortIndicatorShown(True)

        table.horizontalHeader().sectionClicked.connect(partial(self.sort_handler, dictionary = dictionary))
        #table.horizontalHeader().sortIndicatorChanged.connect(self.set_sort_order)

        ## Set number of rows to global variable (generally, 1,000 rows)
        table.setRowCount(row_count)
        
        ## Create list of table headers
        table_headers = ['PV', 'Description', 'Value',
                         'Alarm', 'Saved Value', 'Difference',
                         'Save Timestamp', 'Save', 'Restore', 'Set']

        ## Set column count based on number of headers (10)
        num_headers = len(table_headers)
        table.setColumnCount(num_headers)

        ## Set header labels
        table.setHorizontalHeaderLabels(table_headers)

        return table

    def set_sort_order(self, logicalIndex):
        if SORT_ORDER[logicalIndex] == False:
            SORT_ORDER[logicalIndex] = True
        else:
            SORT_ORDER[logicalIndex] = False

    def sort_handler(self, logicalIndex, dictionary):
        if logicalIndex == 0:
            self.sort_PV(dictionary, logicalIndex)
            self.set_sort_order(logicalIndex)
        elif logicalIndex == 1:
            pass
        elif logicalIndex == 2:
            self.sort_value(dictionary, logicalIndex)
            self.set_sort_order(logicalIndex)
        elif logicalIndex == 3:
            self.sort_alarm(dictionary, logicalIndex)
            self.set_sort_order(logicalIndex)
        elif logicalIndex == 3:
            pass
        elif logicalIndex == 4:
            self.sort_saved_value(dictionary, logicalIndex)
            self.set_sort_order(logicalIndex)
        elif logicalIndex == 5:
            self.sort_difference(dictionary, logicalIndex)
            self.set_sort_order(logicalIndex)
        elif logicalIndex == 6:
            pass
        elif logicalIndex == 7:
            pass
        elif logicalIndex == 8:
            pass
        elif logicalIndex == 9:
            pass

    def sort_dictionary(self, dictionary, values, logicalIndex):
        sorted_by_val = sorted(values.items(), key = lambda x:x[1], 
                               reverse = SORT_ORDER[logicalIndex])
        
        pvs = []
        for i in range(len(sorted_by_val)):
            pv = sorted_by_val[i][0]
            pvs.append(pv)

        saves = []
        for i in range(len(sorted_by_val)):
            save = sorted_by_val[i][1]
            saves.append(save)
        self.clear_table(dictionary)

        for i in range(len(sorted_by_val)):
            ix = str(i)
            dictionary[ix]['PV'].setText(pvs[i])
            dictionary[ix]['Saved Value'].setText(saves[i][1])

    def sort_PV(self, dictionary, logicalIndex):
        pvs = {}

        keys = list(dictionary.keys())
        for key in keys:
            row = dictionary[key]
            pv = row['PV'].text()
            saved = row['Saved Value'].text()

            if pv != '':
                pvs[pv] = (pv, saved)

        self.sort_dictionary(dictionary, pvs, logicalIndex)

    def sort_value(self, dictionary, logicalIndex):
        values = {}

        keys = list(dictionary.keys())
        for key in keys:
            row = dictionary[key]
            value = row['Value'].text()
            pv = row['PV'].text()
            saved = row['Saved Value'].text()
            if pv != '':
                if value != '':
                    if value == 'On' or value == 'In':
                        value = 1
                    elif value =='Off' or value == 'Out':
                        value == 0
                    else:
                        try:
                            value = float(value)
                        except:
                            value = 0
                    values[pv] = (value, saved)

        self.sort_dictionary(dictionary, values, logicalIndex)

    def sort_alarm(self, dictionary, logicalIndex):
        alarms = {}

        keys = list(dictionary.keys())
        for key in keys:
            row = dictionary[key]
            alarm = row['Alarm'].text()
            pv = row['PV'].text()
            if pv != '':
                saved = row['Saved Value'].text()
                if alarm != '':
                    if alarm == 'MINOR':
                        alarm = 1
                    elif alarm == 'MAJOR':
                        alarm = 2
                    elif alarm == 'NO_ALARM':
                        alarm = 3
                    elif alarm == 'INVALID':
                        alarm = 4
                    else:
                        alarm = 4
                    alarms[pv] = (alarm, saved)

        self.sort_dictionary(dictionary, alarms, logicalIndex)

    def sort_difference(self, dictionary, logicalIndex):
        diffs = {}

        keys = list(dictionary.keys())
        for key in keys:
            row = dictionary[key]
            diff = row['Difference'].text()
            pv = row['PV'].text()
            if pv != '':
                saved = row['Saved Value'].text()
                if diff != '':
                    try:
                        diff = float(diff)
                    except:
                        diff = None
                else:
                    diff = 0
                diffs[pv] = (diff, saved)
        
        self.sort_dictionary(dictionary, diffs, logicalIndex)

    def sort_saved_value(self, dictionary, logicalIndex):
        saves = {}

        keys = list(dictionary.keys())
        for key in keys:
            row = dictionary[key]
            saved = row['Saved Value'].text()
            pv = row['PV'].text()
            if pv != '':
                if saved != '':
                    try:
                        save_float = float(saved)
                    except:
                        save_float = 0
                    saves[pv] = (save_float, saved)
                elif saved == '':
                    saves[pv] = (0, saved)

        self.sort_dictionary(dictionary, saves, logicalIndex)

## Function to instantiate dictionary of rows
    def create_dictionary(self, row_count):
        dictionary = {}

        for i in range(row_count):
            ## Create a new sub-dictionary with name i, e.g., dictionary["3"]
            key = str(i)
            ## Each entry in the sub-dictionary is a widget
            dictionary[key] = {'PV': QLineEdit(),
                               'Description': PyDMLabel(),
                               'Value': PyDMLabel(),
                               'Alarm': PyDMLabel(),
                               'Saved Value': PyDMLabel(),
                               'Difference': PyDMLabel(),
                               'Save Timestamp': PyDMLabel(),
                               'Save': QPushButton('Save'),
                               'Restore': QPushButton('Restore'),
                               'Set': PyDMLineEdit()}

            ## Move the PV name to where it needs to go when entered
            dictionary[key]['PV'].editingFinished.connect(partial(self.pass_pv, 
                                                                  dictionary[key]))
            dictionary[key]['PV'].textChanged.connect(partial(self.pass_pv,
                                                              dictionary[key]))

            for widget in ['Value', 'Saved Value']:
                dictionary[key][widget].setProperty('precisionFromPV', True)

            for widget in ['Description', 'Value', 'Alarm',
                           'Saved Value', 'Difference']:
                dictionary[key][widget].setAlignment(QtCore.Qt.AlignCenter)

            ## Disable buttons on launch
            dictionary[key]['Save'].setEnabled(False)
            dictionary[key]['Restore'].setEnabled(False)

            ## Provide actions when the 'Save' or 'Restore' button are clicked
            dictionary[key]['Save'].clicked.connect(partial(self.save_value, 
                                                            dictionary[key]))
            dictionary[key]['Restore'].clicked.connect(partial(self.restore_value,
                                                               dictionary[key]))

        return dictionary

## Function to take PV from QLineEdit to rest of table row
    def pass_pv(self, row):
        ## Get the PV from the line edit widget
        pv = row['PV'].text()
        
        ## Pass the PV name to other widgets
        row['Description'].channel = pv + '.DESC'
        row['Value'].channel = pv
        row['Alarm'].channel = pv + '.SEVR'
        row['Set'].channel = pv

        value_slot = partial(self.calculate_difference, row)
        diff_channel = PyDMChannel(pv, value_slot = value_slot)
        diff_channel.connect()

        desc_widget = row['Description']
        desc_text = desc_widget.text()
        desc_widget.setToolTip(desc_text)

        row['Save'].setEnabled(True)
        row['Restore'].setEnabled(True)

## Function that saves current PV value
    def save_value(self, row):
        ## Get live PV value
        value = row['Value'].text()

        ## Set 'Saved Value' text
        row['Saved Value'].setText(value)

    def calculate_difference(self,  row):
        live = row['Value'].text()
        saved = row['Saved Value'].text()

        if saved != '':
            try:
                live = float(live)
                saved = float(saved)
                diff = live - saved
                if diff < 1:
                    diff = '%g'%(diff)
                    #diff = "{:e}".format(diff)
                else:
                    #diff = format(diff, '.3f')
                    diff = '%g'%(diff)
                row['Difference'].setText(diff)
            except:
                pass

## Function that sets PV to current saved value 
    def restore_value(self, row):
        ## Get PV from line edit
        pv = row['PV'].text()
        
        ## Get saved value
        value = row['Saved Value'].text()

        ## caput the value to the PV if the value exists
        if pv != '':
            if value != '':
                epics.caput(pv, value)

## Function to fill the table with widgets from the dictionary
    def fill_table(self, table, dictionary, row_count):
        ## Get list of sub-dictionary keys, e.g. ['PV', 'Description'...]
        keys = list(dictionary["0"].keys())

        ## For each row...
        for i in range(row_count):

            ## For each column in each row...
            for j in range(10):

                ## Convert the row counter into a str
                row_key = str(i)

                ## The current key string
                sub_key = keys[j]

                ## Grab the widget from the row/column pair
                widget = dictionary[row_key][sub_key]

                ## Set the widget in table at position (i, j)
                table.setCellWidget(i, j, 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()
        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("PV Table")
        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

## Function to create the frame that holds the 'File' actions, 
## e.g., save file, load file.  Also holds search bar 
    def create_file_actions_frame(self, dictionary, table, eget_frame):
        ## Make the frame and set the layout
        frame = QFrame()
        layout = QHBoxLayout()
        frame.setLayout(layout)

        filter_lbl = QLabel('Filter:')

        ## Make the line edit widget that holds the search term
        ## Connect the widget to the filter function
        filter_edit = QLineEdit()
        filter_edit.returnPressed.connect(partial(self.do_filter_action, 
                                                  dictionary, filter_edit,
                                                  table))

        ## Make the search button and connect to the filter function
        filter_btn = QPushButton('Search')
        filter_btn.clicked.connect(partial(self.do_filter_action,
                                           dictionary, filter_edit,
                                           table))

        ## Make a reset button
        reset_btn = QPushButton('Reset')
        reset_btn.clicked.connect(partial(self.reset_filter,
                                          dictionary, filter_edit,
                                          table))

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

        ## Make the load button and connect to the load function
        load_btn = QPushButton('Load file')
        load_btn.clicked.connect(partial(self.load_file, dictionary))

        ## Make the save button and connect to the save function
        save_btn = QPushButton('Save to file')
        save_btn.clicked.connect(partial(self.save_to_file, dictionary))

        ## Make button to show the eget frame
        show_eget_btn = QPushButton('Load with eget')
        show_eget_btn.clicked.connect(partial(self.show_eget_frame,
                                              eget_frame))

        ## Make button to hide the eget frame
        #hide_eget_btn = QPushButton('Hide eget frame')
        #hide_eget_btn.clicked.connect(partial(self.hide_eget_frame,
                                              #eget_frame))

        ## Add the widgets to the frame
        widgets = [filter_lbl, filter_edit, filter_btn,
                   reset_btn,  spacer, show_eget_btn, 
                   load_btn, save_btn]

        for widget in widgets:
            try:
                layout.addWidget(widget)
            except:
                layout.addItem(widget)

        frame.setMaximumHeight(50)

        return frame

## Function that loads CSV file into table 
    def load_file(self, dictionary):
        ## Create dialog window
        file_dialog = QFileDialog()

        ## Create list of potential PV column names
        pv_column_names_0 = ['PV', 'PVs', 'Channel', 'Channels']
        pv_column_names = []

        ## Create list of potential Saved Value column names
        save_value_column_names_0 = ['Saved Value', 'Value', 'Save', 'Saved']
        save_value_column_names = []

        ## Create list of potential Save Timestamp column names
        timestamp_column_names_0 = ['Save Timestamp', 'Save Time', 
                 'Timestamp', 'Time']
        timestamp_column_names = []

        ## List of lists of potential names
        base_names = [pv_column_names_0, save_value_column_names_0, 
                        timestamp_column_names_0]

        ## List of empty lists to be filled with many column names
        column_names = [pv_column_names, save_value_column_names, 
                        timestamp_column_names]

        for i in range(3):
            for name in base_names[i]:
                ## Fill each respective list with all options for column names
                column_names[i].append(name)
                column_names[i].append(name.upper())
                column_names[i].append(name.lower())
        
        ## Try/Except captures error code if no file selected
        try:
            ## Launch the file dialog and get file name
            file_name = file_dialog.getOpenFileName(self, 'Open File', '', 
                                                    'Comma-separated values (*.csv)')

            if file_name[0] != '':
                try:
                    ## Clear the table first
                    self.clear_table(dictionary)

                    ## Read the CSV file into a pandas data frame
                    df = pd.read_csv(file_name[0])               

                    ## Check for PV column.  At first match, break the loop
                    for column in pv_column_names:
                        if column in df.columns:
                            pv_column_match = column
                            pvs = list(df[pv_column_match])
                            break

                    ## For all found PVs, set the line edit in each row
                    for i in range(len(pvs)):
                        ## Sub-dictionary of the current row
                        row = dictionary[str(i)]

                        ## pv_column_match is a string for the PV column name 
                        ## e.g., 'PV', 'channel', 'PVs', etc...
                        pv_name = df[pv_column_match].iloc[i]
                        row['PV'].setText(str(pv_name))

                        ## Check if this row has a matching save value column
                        ## Break loop at first match
                        try:
                            for column in save_value_column_names:
                                if column in df.columns:
                                    save_column_match = column
                                    break

                            ## Saved value from data frame
                            save_value = df[save_column_match].iloc[i]

                            ## Make sure saved value is real
                            if str(save_value) != "nan":
                                row['Saved Value'].setText(str(save_value))

                        except:
                            pass

                        try:
                            ## Check for matching timestamp column
                            for column in timestamp_column_names:
                                if column in df.columns:
                                    timestamp_match = column
                                    break

                            ## Timestamp from data frame
                            time_value = df[timestamp_match].iloc[i]

                            ## Make sure timestamp is real
                            if str(time_value) != "nan":
                                row['Save Timestamp'].setText(str(time_value))

                        except:
                            pass

                except:
                    pass

        except:
            pass

## Function that saves table to a CSV file
    def save_to_file(self, dictionary):
        rows_with_data = []
        keys = list(dictionary.keys())
        for key in keys:
            row = dictionary[key]
            pv = row['PV'].text()
            if pv != '':
                rows_with_data.append(key)

        data = {}
        headers = ['PV', 'Description', 'Value',
                   'Alarm', 'Saved Value', 'Difference',
                   'Save Timestamp']
        for row in rows_with_data:
            data[row] = {}
            for header in headers:
                value = dictionary[row][header].text()
                if value == "":
                    value = "N/A"
                data[row][header] = value

        df = pd.DataFrame.from_dict(data, orient='index')

        file_dialog = QFileDialog()
        file_dialog.setDefaultSuffix('.csv')
        try:        
            csv_file = file_dialog.getSaveFileName(self, 'Save File','',
                                                   'Comma-separated values (*.csv)')[0]
            df.to_csv(csv_file)

        except IOError:
            a = 1 

    def create_eget_frame(self, dictionary):
        frame = QFrame()
        layout = QHBoxLayout()
        frame.setLayout(layout)

        eget_edit = QLineEdit()
        eget_edit.setPlaceholderText('Enter eget command')
        eget_edit.returnPressed.connect(partial(self.run_eget_command, eget_edit,
                                                dictionary))
        eget_run_btn = QPushButton('Run')
        eget_run_btn.clicked.connect(partial(self.run_eget_command, eget_edit,
                                             dictionary))

        widgets = [eget_edit, eget_run_btn]
        for widget in widgets:
            layout.addWidget(widget)

        return frame

    def show_eget_frame(self, frame):
        frame.show()

    def hide_eget_frame(self, frame):
        frame.hide()

    def run_eget_command(self, line_edit, dictionary):
        eget_command = line_edit.text()

        is_eget_command = eget_command.startswith('eget')
        if is_eget_command:
            #try:
            stream = os.popen(eget_command)
            output = stream.read()
            split_lines = output.splitlines()
            pv_list = []
            for line in split_lines:
                line = str(line)
                line = ''.join(line.split())
                if ':' in line:
                    pv_list.append(line)
            
            for i in range(len(pv_list)):
                pv = pv_list[i]
                is_string = isinstance(pv, str)
                if is_string:
                    row = dictionary[str(i)]
                    row['PV'].setText(pv)
            #except:
             #   pass
        else:
            print('Error: Not an eget command')
        
    def reset_filter(self, dictionary, line_edit, table):
        line_edit.setText('')
        num_rows = int(table.rowCount())
        for i in range(num_rows):
            table.showRow(i)

## Function that hides rows that do not match the filter text
    def do_filter_action(self, dictionary, line_edit, table):
        search_term = line_edit.text()
        keys = list(dictionary.keys())

        if search_term == "":
            ## Reset search
            for key in keys:
                table.showRow(int(key))
        else:
            for key in keys:
                row = dictionary[key]
                pv = row['PV'].text()
                if search_term.upper() not in pv.upper():
                    table.hideRow(int(key))
                else:
                    table.showRow(int(key))

## Function that creates the 'Table' actions frame, e.g.,
## 'Clear Table', 'Clear Saves', 'Save all', 'Restore All'
    def create_table_actions_frame(self, dictionary, table):
        frame = QFrame()
        layout = QHBoxLayout()
        frame.setLayout(layout)        

        clear_frame = QFrame()
        clear_layout = QVBoxLayout()
        clear_frame.setLayout(clear_layout)

        clear_table_btn = QPushButton('Clear Table')
        clear_table_btn.clicked.connect(partial(self.clear_table, dictionary))

        clear_saved_values_btn = QPushButton('Clear Saved Values')
        clear_saved_values_btn.clicked.connect(partial(self.clear_saved_values,
                                                       dictionary))

        clear_layout.addWidget(clear_table_btn)
        clear_layout.addWidget(clear_saved_values_btn)

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

        hide_save_btn = QPushButton('Hide Save Columns')
        hide_save_btn.clicked.connect(partial(self.hide_save_columns, table))

        show_save_btn = QPushButton('Show Save Columns')
        show_save_btn.clicked.connect(partial(self.show_save_columns, table))

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

        save_frame = QFrame()
        save_layout = QGridLayout()
        save_frame.setLayout(save_layout)

        save_all_btn = QPushButton('Save All')
        save_all_btn.clicked.connect(partial(self.save_all_values, dictionary))

        restore_all_btn = QPushButton('Restore All')
        restore_all_btn.clicked.connect(partial(self.restore_all_values, dictionary))
        
        save_filtered_btn = QPushButton('Save Filtered Only')
        save_filtered_btn.clicked.connect(partial(self.save_filtered_values,
                                                  dictionary, table))

        restore_filtered_btn = QPushButton('Restore Filtered Only')
        restore_filtered_btn.clicked.connect(partial(self.restore_filtered_values,
                                                     dictionary, table))

        save_layout.addWidget(save_all_btn, 0, 0)
        save_layout.addWidget(restore_all_btn, 0, 1)
        save_layout.addWidget(save_filtered_btn, 1, 0)
        save_layout.addWidget(restore_filtered_btn, 1, 1)

        widgets = [clear_frame, spacer1,
                   hide_save_btn, show_save_btn,
                   spacer2, save_frame]

        for widget in widgets:
            try:
                layout.addWidget(widget)
            except:
                layout.addItem(widget)

        frame.setMaximumHeight(80)

        return frame

## Function that saves all rows
    def save_all_values(self, dictionary):
        keys = list(dictionary.keys())
        for key in keys:
            row = dictionary[key]
            pv = row['PV'].text()
            if pv:
                self.save_value(row)

    def save_filtered_values(self, dictionary, table):
        keys = list(dictionary.keys())
        for key in keys:
            hidden = table.isRowHidden(int(key))
            if not hidden:
                row = dictionary[key]
                pv = row['PV'].text()
                if pv:
                    self.save_value(row)

    def restore_filtered_values(self, dictionary, table):
        keys = list(dictionary.keys())
        for key in keys:
            hidden = table.isRowHidden(int(key))
            if not hidden:
                row = dictionary[key]
                pv = row['PV'].text()
                value = row['Saved Value']
                if pv != '':
                    if value !='':
                        self.restore_value(row)

## Function that restores all saved values 
    def restore_all_values(self, dictionary):
        keys = list(dictionary.keys())
        for key in keys:
            row = dictionary[key]
            pv = row['PV'].text()
            value = row['Saved Value']
            if pv != '':
                if value != '': 
                    self.restore_value(row)

## Function that clears all data from table
    def clear_table(self, dictionary):
        keys = list(dictionary.keys())

        cell_widgets = ['PV', 'Description', 'Value',
                        'Alarm', 'Saved Value', 'Difference',
                        'Save Timestamp']

        for key in keys:
            row = dictionary[key]
            for widget in cell_widgets:
                row[widget].setText('')
            row['Description'].channel = ''
            row['Value'].channel = ''
            row['Alarm'].channel = ''

## Function that clears all saved values from table
    def clear_saved_values(self, dictionary):
        keys = list(dictionary.keys())
        for key in keys:
            row = dictionary[key]
            row['Saved Value'].setText('')
            row['Save Timestamp'].setText('')

    def hide_save_columns(self, table):
        for i in range(4, 9):
            table.setColumnHidden(i, True)

    def show_save_columns(self, table):
        for i in range(4, 9):
            table.setColumnHidden(i, False)

## Main function that creates the user interface
    def create_UI(self, row_count):
        dictionary = self.create_dictionary(row_count)
        table = self.create_table(row_count, dictionary)
        header = self.create_header_frame()
        eget_frame = self.create_eget_frame(dictionary)
        file_actions = self.create_file_actions_frame(dictionary, 
                                                      table, eget_frame)
        #table = self.create_table(ROW_COUNT)
        table_actions = self.create_table_actions_frame(dictionary, table)

        self.fill_table(table, dictionary, row_count)

        widgets = [header, file_actions, table,
                   table_actions]

        for widget in widgets:
            self.main_layout.addWidget(widget)

        self.clear_table(dictionary)

