import json
import os
from pydm import Display
from pydm.PyQt.QtGui import (QVBoxLayout, QHBoxLayout, QGroupBox,
    QLabel, QLineEdit, QPushButton, QScrollArea, QFrame,
    QApplication, QWidget, QAction, QIcon)
from pydm.PyQt import QtCore
from pydm.widgets import PyDMEmbeddedDisplay
from pydm.utilities.iconfont import IconFont
from pydm.main_window import PyDMMainWindow
from collections import OrderedDict
import subprocess


class evrGlobal(Display):
    def __init__(self, parent=None, args=[], macros=None):
        super(evrGlobal, self).__init__(parent=parent, args=args, macros=None)
        # Placeholder for data to filter
        self.data = []
        # Reference to the PyDMApplication
        self.app = QApplication.instance()
        # Assemble the Widgets
        self.setup_ui()
        # Load data from file
        self.load_data()
        # Load the table initially
        self.initial_load()

        self.main_win = None

        for window in QApplication.instance().topLevelWidgets():
            if isinstance(window, PyDMMainWindow):
                main_win = window
                break

        # Adding button to Main window bar
        btn_reset = QAction(self)
        btn_reset.setText("Reset")
        btn_reset.setIcon(IconFont().icon("window-close"))
        btn_reset.triggered.connect(self.reset_all)
        main_win.ui.navbar.addAction(btn_reset)

    def minimumSizeHint(self):
        # This is the default recommended size
        # for this screen
        return QtCore.QSize(750, 550)

    def ui_filepath(self):
        # No UI file is being used
        return None

    def setup_ui(self):

        # Create the main layout
        main_layout = QVBoxLayout()
        self.setLayout(main_layout)

        # Create a Label to be the title
        lbl_title = QLabel("Global EVR Reset")
        # Add some StyleSheet to it
        lbl_title.setStyleSheet("\
            QLabel {\
                qproperty-alignment: AlignCenter;\
                border: 1px solid #FF17365D;\
                border-top-left-radius: 15px;\
                border-top-right-radius: 15px;\
                background-color: #FF17365D;\
                padding: 5px 0px;\
                color: rgb(255, 255, 255);\
                max-height: 25px;\
                font-size: 14px;\
            }")

        # Add the title label to the main layout
        main_layout.addWidget(lbl_title)

        # Create the Search Panel layout
        search_layout = QHBoxLayout()

        # Create a GroupBox with "Filtering" as Title
        gb_search = QGroupBox(parent=self)
        gb_search.setTitle("Filtering")
        gb_search.setLayout(search_layout)

        # Create a label, line edit and button for filtering
        lbl_search = QLabel(text="Filter: ")
        self.txt_filter = QLineEdit()
        self.txt_filter.returnPressed.connect(self.do_search)

        # Search button
        btn_search = QPushButton()
        btn_search.setText("Search")
        btn_search.clicked.connect(self.do_search)

        # Add the created widgets to the layout
        search_layout.addWidget(lbl_search)
        search_layout.addWidget(self.txt_filter)
        search_layout.addWidget(btn_search)

        # Add the Groupbox to the main layout
        main_layout.addWidget(gb_search)

        # Create the Results Layout
        self.results_layout = QVBoxLayout()
        self.results_layout.setContentsMargins(0, 0, 0, 0)

        # Create a Frame to host the results of search
        self.frm_result = QFrame(parent=self)
        self.frm_result.setLayout(self.results_layout)

        # Create a ScrollArea so we can properly handle
        # many entries
        scroll_area = QScrollArea(parent=self)
        scroll_area.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        scroll_area.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        scroll_area.setWidgetResizable(True)

        # Add the Frame to the scroll area
        scroll_area.setWidget(self.frm_result)

        # Add the scroll area to the main layout
        main_layout.addWidget(scroll_area)

    def load_data(self):
        '''
        run an eget command to read the connected devices
        pass the command to terminal and store the output
        '''
        eget_command = "eget -t -s ds -a name=EVR:%:%:LINKERRCNT"
        process = subprocess.Popen(
            eget_command.split(), stdout=subprocess.PIPE)
        # For each line in the file...
        device_dict = OrderedDict()
        for row in process.stdout.readlines():
            if not row.strip('\n'):
                continue
            item = row.split(":")
            item.remove('LINKERRCNT\n')
            entry = ":".join(item)
            if entry not in device_dict:
                device_dict[entry]=[]
        self.data = device_dict.keys()

    def do_search(self):
        # First lets clear the old connections
        self.app.close_widget_connections(self.frm_result)

        # For each widget inside the results frame, lets destroy them
        for widget in self.frm_result.findChildren(QWidget):
            widget.setParent(None)
            widget.deleteLater()

        # Grab the filter text
        filter_text = self.txt_filter.text()

        # For every entry in the dataset...
        for entry in self.data:
            # Check if they match our filter
            if filter_text.upper() not in entry.upper():
                continue
            # Create a PyDMEmbeddedDisplay for this entry
            disp = PyDMEmbeddedDisplay(parent=self)
            disp.macros = json.dumps({"DEVICE":entry})
            base_dir = os.path.dirname(os.path.realpath(__file__))
            disp.filename = os.path.join(base_dir, 'inlineEvrDevice.ui')
            disp.setMinimumWidth(700)
            disp.setMinimumHeight(30)
            disp.setMaximumHeight(100)
            # Add the Embedded Display to the Results Layout
            self.results_layout.addWidget(disp)
        # Recursively establish the connection for widgets
        # inside the Results Frame
        self.app.establish_widget_connections(self.frm_result)

    def initial_load(self):
        for entry in self.data:
            # Create a PyDMEmbeddedDisplay for this entry
            disp = PyDMEmbeddedDisplay(parent=self)
            disp.macros = json.dumps({"DEVICE":entry})
            base_dir = os.path.dirname(os.path.realpath(__file__))
            disp.filename = os.path.join(base_dir, 'inlineEvrDevice.ui')
            disp.setMinimumWidth(700)
            disp.setMinimumHeight(30)
            disp.setMaximumHeight(100)
            # Add the Embedded Display to the Results Layout
            self.results_layout.addWidget(disp)

    # This is for the Global Reset
    def reset_all(self):
        process = subprocess.Popen(["bash", "./evrGlobalReset.sh"])
