# -*- coding: utf-8 -*-
'''
==============================================================

 Abs:
     Reads eget output and creates a pyqt tree.  A save button
     includes fucntionality to save bsa devices to .mat file

 Name: bsa_tree

 Facility:  SLAC/LCLS

 Auth: 06-Jun-2018, Dan Sciortino (disco@slac.stanford.edu)
==============================================================
'''

from PyQt5 import QtCore, QtWidgets
from collections import OrderedDict
from bsa_save_window import pop_up
from bsa_error_window import error_up
import subprocess
import argparse
import atexit
import os
import socket
import signal
import time


class Ui_MainWindow(object):

    def get_args(self):
        '''
        requiring two macros to be defined. This gets pasted to the
        bsa_plot window
        '''
        parse = argparse.ArgumentParser()
        parse.add_argument('-m', nargs=3, dest='macro')
        macros_dictionary = vars(parse.parse_args())
        macros = macros_dictionary.get('macro')
        mdid = macros[0]
        md = macros[1]
	unit = macros[2]
        return mdid, md, unit
        
    def get_bsa(self):
        try:
            '''
            run an eget command to read the connected devices
            pass the command to terminal and store the output
            '''
            command = "eget -ts ds -a sort=z -a tag=LCLS.BSA.rootnames"
            process = subprocess.Popen(
                command.split(), stdout=subprocess.PIPE)
            '''
            catch error if eget cant be ran
            '''
        except OSError:
            self.error_up = QtWidgets.QMainWindow()
            self.ui = error_up()
            self.ui.setupUi(self.error_up)
            self.error_up.show()
            time.sleep(10)
            sys.exit(1)
        '''
        set up dictionary and start to read lines from the variable
        '''
        bsa_dict = OrderedDict()
        for row in process.stdout.readlines():
            '''
            If trying to read a blank line skip it
            split each line to read the areas
            '''
            if not row.rstrip():
                continue
            field = row.split(":")
            '''
            Check to see if the area already exists in the dict
            if it doesnt add the key and value
            if it does add the value to the established key
            '''
            if field[1] not in bsa_dict:
                bsa_dict[field[1]] = []
                temp_field = field
                s = ':'.join(temp_field)
                bsa_dict[field[1]].append(s.strip('\"\r\n'))
            elif field[1] in bsa_dict:
                temp_field = field
                s = ':'.join(temp_field)
                bsa_dict[field[1]].append(s.strip('\"\r\n'))
        return bsa_dict

    '''
    read the keys then read all values associated
        send keys to sector label
        all values to pv label
    print on top level item
    '''

    def fill_tree(self, input_dict):
        for key, val in input_dict.iteritems():
            sector_label = QtWidgets.QTreeWidgetItem(self.bsa_view)
            sector_label.setText(0, key)
            for v in val:
                pv_label = QtWidgets.QTreeWidgetItem(sector_label)
                pv_label.setText(0, v)
            self.bsa_view.addTopLevelItem(sector_label)
    '''
    Find the user selected value in the tree
    pass pv and the macros to function to make
    a plot window uses edm and plotBSA
    save the pids of the displays to a list
    '''

    def bsa_plot(self, child_pid):
        getSelected = self.bsa_view.selectedItems()
        baseNode = getSelected[0]
        pv = baseNode.text(0)
        if ':' in pv:
            command = 'edm -x -eolc -m MDID=' + self.mdid + \
                ',PV=' + pv + ',MD=' + self.md + ',TPG_UNIT=' + self.unit + ' plotBSA_TPG.edl'
            display = subprocess.Popen(command.split())
            self.add_child_pids(self.child_pid, display.pid)
	    print command

    '''
    update pid to list
    '''

    def add_child_pids(self, child_pid, pid):
        self.child_pid.append(pid)
        # print child_pid
        return child_pid

    '''
    Save the BSA devices list
    '''

    def save_bsa(self):
        process = subprocess.Popen(["bash", "./matlab_launcher.sh", str(self.mdid)])
        '''
        check the process to see if its running
        '''
        while process.poll() is None:
            time.sleep(1)

        '''
        get the error code returned from the bash script
        '''
        return_code = process.returncode
        if return_code == 0:
            try:
                self.pop_up = QtWidgets.QMainWindow()
                self.ui = pop_up()
                self.ui.setupUi(self.pop_up)
                self.pop_up.show()
            except TypeError:
                print "Could Not Make a New Window"
        else:
            print "Matlab Error"

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(310, 700)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        # makes the close button
        self.Close = QtWidgets.QPushButton(self.centralwidget)
        self.Close.setGeometry(QtCore.QRect(180, 600, 100, 20))
        self.Close.setObjectName("Close")

        # makes the save button
        self.Save = QtWidgets.QPushButton(self.centralwidget)
        self.Save.setGeometry(QtCore.QRect(30, 600, 100, 20))
        self.Save.setObjectName("Save")
        self.Save.clicked.connect(self.save_bsa)

        # makes the treewidget item
        self.bsa_view = QtWidgets.QTreeWidget(self.centralwidget)
        self.bsa_view.setGeometry(QtCore.QRect(20, 50, 260, 520))
        self.bsa_view.setObjectName("bsa_view")
        self.bsa_view.headerItem().setText(0, "")
        self.bsa_view.itemDoubleClicked.connect(self.bsa_plot)

        # Makes the status bar for the application
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 310, 20))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)

        # Makes the status bar for the application
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        # Makes the EDEF label
        self.EDEF_label = QtWidgets.QLabel(self.centralwidget)
        self.EDEF_label.setGeometry(QtCore.QRect(70, 20, 58, 15))
        self.EDEF_label.setObjectName("EDEF_label")

        # Makes the EDEF number
        self.EDEF_value = QtWidgets.QLabel(self.centralwidget)
        self.EDEF_value.setGeometry(QtCore.QRect(140, 20, 58, 15))
        self.EDEF_value.setText("")
        self.EDEF_value.setObjectName("EDEF_value")

        '''
        make the dictionary from stdout and
        populate the tree data
        make a list of pids
        '''
        try:
            self.mdid, self.md, self.unit = self.get_args()
        except:
            sys.exit('Macros Missing from runtime call')
        self.dict = self.get_bsa()
        self.fill_tree(self.dict)
        self.child_pid = []

        self.retranslateUi(MainWindow)

        # Connect the close window slot to the close button
        self.Close.clicked.connect(MainWindow.close)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    '''
    Makes the labels for each of the objects
    '''

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "BSA Viewer"))
        self.Close.setText(_translate("MainWindow", "Close"))
        self.EDEF_label.setText(_translate("MainWindow", "BSA"))
        self.EDEF_value.setText(_translate("MainWindow", self.mdid))
        self.Save.setText(_translate("MainWindow", "Save..."))

    '''
    Before close kill all started edm displays
    '''

    def kill_child_pids(self):
        try:
            for child in self.child_pid:
                os.kill(child, signal.SIGKILL)
        except IndexError:
            # If the user didn't open a plot we dont need to kill a plot
            pass


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    ret = app.exec_()
    atexit.register(ui.kill_child_pids)
    sys.exit()
