#!/afs/slac/g/acctest/package/python/current/bin/python

###############################################################################
# Name: bake_schedule.py                                                      #
# Author: Shawn Alverson                                                      #
# Created: 9/20/2016                                                          #
#                                                                             #
# Purpose: Import/Export csv table of bake schedule parameters into/from      #
#          EPICS for integration with the PLC.                                #
#                                                                             #
###############################################################################

from PyQt4.QtGui import *
from PyQt4.QtCore import *
import csv
from epics import caget, caput


class MainWindow(QWidget):
    def __init__(self, station=5, config=None, parent=None):
        super(MainWindow, self).__init__(parent)
        
        self.main_widget = QWidget()
        
        self.station = 'BS:B44:BS0' + str(station)
        self.elements = ( ('Line_Desc', 'str'), ('Ves_Rec_P', 'float'), ('Ves_Hold_P', 'float'), \
                          ('Ves_Max_P', 'float'), ('Tube_Rec_P', 'float'), ('Tube_Hold_P', 'float'), \
                          ('Tube_Max_P', 'float'), ('Win_Rec_P', 'float'), ('Win_Hold_P', 'float'), \
                          ('Win_Max_P', 'float'), ('Oven_Temp', 'float'), ('Oven_Ramp', 'float'), \
                          ('Oven_Temp_Cont', 'float'), ('Fil_Amps', 'float'), ('Fil_Ramp', 'float'), \
                          ('Min_Time_Next', 'float'), ('Max_Time_Next', 'float'), \
                          ('Ves_Cooling', 'enum', ("On","Off")), ('Man_Heat_Tape', 'enum', ("On","Off")), \
                          ('Max_Time_Action', 'enum', ("Ignore","Notify","Abort")), \
                          ('Op_Intervention', 'enum', ("Yes","No")), ('Comment', 'str') )
        #self.element_types = [ str, float, float, float, float, float, float, float, float, float, float, float, \
        #                       float, float, float, float, float, float, float, float, float, str ]
        self.lines = 40
        self.config_num = 11
        self.stored = True

        self.setupUI()
        if config is None: 
            self.load_file()
        else:
            self.config_menu.setValue(int(config))
            self.get_config(config)
        
    def setupUI(self):
        self.setStyleSheet("QPushButton {border: 1px solid gray;"
                                        "border-radius: 4px;"
                                        "padding: 1px;"
	                                "margin: 0px;"  
                                        "background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                                                                    "stop:0 #eeeeee, "
                                                                    "stop:0.5 #cccccc, "
                                                                    "stop:1 #eeeeee);}"
                           "QPushButton:pressed {color: #222222;"
                                                "border: 2px inset #777777;"	
                                                "background: qlineargradient(x1:0, y1:0, x2:0, y2:1, "
                                                "stop:0 #cccccc, "
                                                "stop:0.5 #eeeeee, "
                                                "stop:1 #cccccc);}"
                           "QPushButton:hover {border: 1px outset black;}"
                           "QProgressBar {border: 2px inset gray;"
                                         "border-radius: 4px;}"
                           "QProgressBar:chunk {background-color: #05b8cc;}")
                           #"QSpinBox {border: 1px solid gray;"
                           #          "border-radius: 5px;}"
                           #"QSpinBox:up-button {background-color: lightGray;"
                           #                    "border: 1px outset gray;"
                           #                    "border-bottom-width: 1px;"
                           #                    "border-top-left-radius: 2px;"
                           #                    "border-top-right-radius: 2px;}"
                           #"QSpinBox:down-button {background-color: lightGray;"
                           #                      "border: 1px outset gray;"
                           #                      "border-top-width: 0;"
                           #                      "border-bottom-left-radius: 2px;"
                           #                      "border-bottom-right-radius: 2px;}")
        
        heading_font = QFont()
        heading_font.setPointSize(20)
        heading_font.setWeight(75) # Bold = 75

        station_label = QLabel(self.station)
        station_label.setFont(heading_font)
        station_label.setStyleSheet("QLabel {color: blue;}")
        
        get_epics_button = QPushButton('Get PLC Config')
        QObject.connect(get_epics_button, SIGNAL('clicked()'), self.get_epics_config)
        
        self.epics_save_button = QPushButton('Save to PLC')
        QObject.connect(self.epics_save_button, SIGNAL('clicked()'), self.save_to_epics)
        
        csv_open_button = QPushButton('Open CSV')
        QObject.connect(csv_open_button, SIGNAL('clicked()'), self.load_file)        
        
        csv_save_button = QPushButton('Save to CSV')
        QObject.connect(csv_save_button, SIGNAL('clicked()'), self.save_to_csv)
        
        button_layout = QHBoxLayout()
        button_layout.addWidget(get_epics_button)
        button_layout.addWidget(self.epics_save_button)
        button_layout.addWidget(csv_open_button)
        button_layout.addWidget(csv_save_button)
        
        header_layout = QHBoxLayout()
        header_layout.addWidget(station_label)
        #header_layout.addLayout(config_layout)
        header_layout.addLayout(button_layout)
        
        name_label = QLabel('Name:')
        name_label.setFixedWidth(45)
        self.config_name = QLineEdit()
        name_layout = QHBoxLayout()
        name_layout.addWidget(name_label, Qt.AlignRight)
        name_layout.addWidget(self.config_name, Qt.AlignLeft)
        
        config_label = QLabel('Config #:')
        config_label.setFixedWidth(60)
        self.config_menu = QSpinBox()
        self.config_menu.setMinimum(0)
        self.config_menu.setMaximum(self.config_num-1)
        self.config_menu.setFixedWidth(40)
        self.config_menu.setFixedHeight(25)
        self.config_widget = QWidget()
        self.config_widget.setFixedWidth(120)
        self.config_widget.setFixedHeight(45)
        config_layout = QHBoxLayout(self.config_widget)
        config_layout.addWidget(config_label, Qt.AlignRight)
        config_layout.addWidget(self.config_menu, Qt.AlignLeft)       
        
        self.mode_button = QPushButton('Stored')
        self.mode_button.setCheckable(True)
        QObject.connect(self.mode_button, SIGNAL('toggled(bool)'), self.mode_toggled)
        
        sub_header_layout = QHBoxLayout()
        sub_header_layout.addLayout(name_layout)
        sub_header_layout.addWidget(self.mode_button)
        sub_header_layout.addWidget(self.config_widget)
        
        self.table = QTableWidget(self.lines,22,self.main_widget)
        self.table.setHorizontalHeaderLabels([label[0].replace('_','\n') for label in self.elements])
        self.table.setVerticalHeaderLabels(map(str, range(0,self.lines)))
        #for row in range(0,self.table.rowCount()-1,1):
        #    for col in range(0,self.table.columnCount()-1,1):
        #        self.table.setItem(row,col,QTableWidgetItem(""))
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.resizeColumnsToContents()
        
        main_layout = QVBoxLayout(self)
        main_layout.addLayout(header_layout)
        main_layout.addLayout(sub_header_layout)
        main_layout.addWidget(self.table)

        self.setLayout(main_layout)

    def load_file(self):
        from os.path import exists, basename

        file = QFileDialog.getOpenFileName(self, "Open CSV", "","CSV (*.csv);;All files (*)")
        #print file
        if not file.isEmpty() and exists(file):
            self.config_name.setText(basename(str(file)).split('.')[0])
            with open(str(file), 'rb') as csvfile:
                self.table.setVisible(False)
                full_data = csv.reader(csvfile)
                row = 0
                for row_data in full_data:
                    col = 0
                    for entry in row_data:
                        self.table.setItem(row,col,QTableWidgetItem(entry))
                        col += 1
                    row += 1
                self.table.resizeColumnsToContents()
                self.table.setVisible(True)

    def get_epics_config(self, config=None):
        from time import sleep
        
        if self.stored:
            if config is None: config = int(self.config_menu.value())
            msg_string = 'stored config #' + str(config)
            pv_prefix = ':Stored_'
            name_pv = ':BUFFER_NAME'
        else:
            config = -1
            msg_string = 'active config'
            pv_prefix = ':Active_'
            name_pv = ':ACTIVE_NAME'
        
        steps = (self.lines * len(self.elements)) + 50
        progress = QProgressDialog("Retrieving " + msg_string + " from EPICS...","Abort",0,steps)
        progress.setWindowModality(Qt.WindowModal)
        self.backup = {}
        QObject.connect(progress, SIGNAL('canceled()'), self.abort_load)
        
        if self.stored: caput(self.station + ':LOAD_CONFIG_TO_BUFFER', config)
        
        loaded_config = -1
        loop_cnt = 0
        while not self.stored and loaded_config != config:
            loaded_config = caget(self.station + ':STORED_CONFIG_LOADED')
            sleep(1)
            loop_cnt += 1
            if loop_cnt > 10:
                progress.cancel()
                print 'Timed out, aborting...'
                break
        #print 'Config ' + str(config) + ' loaded!'
        progress.setValue(50)
        
        name = caget(self.station + name_pv)
        self.config_name.setText(QString(name))
        for row in range(0,self.lines,1):
            col = 0
            for element in self.elements:
                pv = element[0]
                #print self.station + ':Stored_' + pv.upper() + str(row) + '_REQ'
                if progress.wasCanceled(): break
                value = caget(self.station + pv_prefix + pv.upper() + str(row) + '_REQ')
                #print value
                #self.table_data[row][col].setText(value)
                if self.table.item(row,col) is not None:
                    self.backup[self.table.item(row,col).text()] = [row,col] 
                self.table.setItem(row,col,QTableWidgetItem(str(value)))
                col += 1
                progress.setValue(progress.value() + 1)
        self.table.setVisible(False)
        self.table.resizeColumnsToContents()
        self.table.setVisible(True)

    def save_to_epics(self):
        config = int(self.config_menu.value())
        
        reply = QMessageBox.question(self, 'Warning!', 'Are you sure you wish to overwrite config ' + str(config) + '?', \
                                     QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.caput_pvs(config)

    def caput_pvs(self, config):
        from time import sleep        
        
        steps = (self.lines * len(self.elements)) + 50
        progress = QProgressDialog("Saving data to EPICS config #" + str(config) + "...","Abort",0,steps)
        progress.setWindowModality(Qt.WindowModal)
        self.backup = {}
        QObject.connect(progress, SIGNAL('canceled()'), self.abort_save)
        
        caput(self.station + ':LOAD_CONFIG_TO_BUFFER', config)        
        
        loaded_config = -1
        loop_cnt = 0
        while loaded_config != config:
            loaded_config = caget(self.station + ':STORED_CONFIG_LOADED')
            sleep(1)
            loop_cnt += 1
            if loop_cnt > 10:
                progress.cancel()
                print 'Timed out, aborting...'
                break
        #print 'Config ' + str(config) + ' loaded!'
        progress.setValue(50)
        
        caput(self.station + ':BUFFER_NAME', str(self.config_name.text()))
        for row in range(0,self.lines,1):
            col = 0
            for element in self.elements:
                if progress.wasCanceled(): break
                
                pv = element[0]
                if self.table.item(row,col) is None:
                    if element[1] == 'str':
                        value = ""
                    else:
                        value = "0"
                else:
                    value = str(self.table.item(row,col).text()).title()
                
                if element[1] == 'float':
                    if value is None or value == "" or not self.is_number(value): 
                        value = float(0.0)
                    else:
                        value = float(value)
                elif element[1] == 'enum':
                    if value == "": 
                        value = 0
                    else:
                        if value in element[2]:
                            value = value.title()
                        elif self.is_number(value) and int(float(value)) < len(element[2]):
                            value = int(float(value))
                        elif len(value) == 1 and any(string[0] == value for string in element[2]):
                            value = next((string for string in element[2] if string[0] == value), element[2][0])
                        else:
                            print str(value) + ' is invalid for ' + pv + ' with type: ' + str(type(value))
                            progress.setValue(progress.value() + 1)
                            continue
                else:
                    value = value[:39]  # Character limited to 40 for strings

                pv = self.station + ':Stored_' + pv.upper() + str(row) + '_REQ'
                
                self.backup[pv] = caget(pv)
                #print pv, value, type(value)
                caput(pv, value)
                
                col += 1
                progress.setValue(progress.value() + 1)
        # Toggle Save PV to push schedule into PLC
        caput(self.station + ':SAVE_SCHEDULE', 1)
        caput(self.station + ':SAVE_SCHEDULE', 0)
        progress.deleteLater()

    def save_to_csv(self):
        from os import path
        
        name = str(self.config_name.text())
        path, ext = path.splitext(name)
        if not path: 
            if self.stored:
                name = 'Station_' + str(self.station[-1]) + '_Stored_Config_#' + str(self.config_menu.value())
            else:
                name = 'Station_' + str(self.station[-1]) + '_Active_Config'
        if not ext: name = name + '.csv'
        
        file = QFileDialog.getSaveFileName(self, "Save CSV", name, "CSV (*.csv)")
        
        if not file.isEmpty():
            #print 'Saving data to ' + file
            with open(str(file), 'wb') as csvfile:
                writer = csv.writer(csvfile)
                for row in range(0,self.lines,1):
                    row_data = []
                    for col in range(0,len(self.elements),1):
                        cell_item = self.table.item(row,col)
                        if cell_item is not None:
                            row_data.append(cell_item.text())
                        else:
                            row_data.append("")
                    writer.writerow(row_data)
     
    def abort_load(self):
        if any(self.backup):
            for key in self.backup:
                self.table.setItem(self.backup[key][0],self.backup[key][1],QTableWidgetItem(key))
                self.table.setVisible(False)
                self.table.resizeColumnsToContents()
                self.table.setVisible(True)

    def abort_save(self):
        if any(self.backup):
            for key in self.backup:
                caput(key, self.backup[key])
                self.table.setVisible(False)
                self.table.resizeColumnsToContents()
                self.table.setVisible(True)
    
    def mode_toggled(self, toggled):
        if toggled:
            self.mode_button.setText('Stored')
            self.stored = True
            self.config_widget.setVisible(True)
            self.epics_save_button.setVisible(True)
        else:
            self.mode_button.setText('Active')
            self.stored = False
            self.config_widget.setVisible(False)
            self.epics_save_button.setVisible(False)
    
    def is_number(self, string):
        try:
            float(string)
            return True
        except ValueError:
            return False

if __name__ == "__main__":
    from sys import argv, exit
    
    args = len(argv)
    if args < 2:
        station = 5
        config = None
    elif args == 2:
        station = argv[1]
        config = None
    elif args >= 3:
        station = argv[1]
        config = argv[2]
    app = QApplication(argv)
    window = MainWindow(station, config)
    window.show()
    window.raise_()
    exit(app.exec_())
