#!/usr/bin/env python

import sys
from datetime import datetime
from PyQt4 import QtGui, QtCore
import pyut_framework as pyutf
import pyut_xml as pyutx

class StyledLabel(QtGui.QLabel):
    def __init__(self):
        super(StyledLabel, self).__init__()
        self.setFrameShape(QtGui.QFrame.StyledPanel)
    
class TreeNode(object):
    def __init__(self, parent, row, data):
        self.parent = parent
        self.row = row
        self.data = data
        self.subnodes = [TreeNode(self, index, elem) for index, elem in enumerate(self.data.get_children())]

class TreeModel(QtCore.QAbstractItemModel):
    """Tree model for displaying TestItem objects in a tree view."""
    HEADERS = ["Name", "Status", "Duration[s]"]
    
    def __init__(self, root_nodes):
        QtCore.QAbstractItemModel.__init__(self)
        self._root_nodes = [TreeNode(None, index, elem) for index, elem in enumerate(root_nodes)]

    def index(self, row, column, parent):
        if not parent.isValid():
            return self.createIndex(row, column, self._root_nodes[row])
        parent_node = parent.internalPointer()
        return self.createIndex(row, column, parent_node.subnodes[row])

    def parent(self, index):
        if not index.isValid():
            return QtCore.QModelIndex()
        node = index.internalPointer()
        if node.parent is None:
            return QtCore.QModelIndex()
        else:
            return self.createIndex(node.parent.row, 0, node.parent)

    def rowCount(self, parent):
        if not parent.isValid():
            return len(self._root_nodes)
        node = parent.internalPointer()
        return len(node.subnodes)
    
    def columnCount(self, parent):
        return len(TreeModel.HEADERS)
    
    def data(self, index, role):
        if not index.isValid():
            return None
        node = index.internalPointer()
        if role == QtCore.Qt.DisplayRole:
            if index.column() == 0:
                return node.data.name
            elif index.column() == 1:
                if node.data.status:
                    return str(node.data.status)
            elif index.column() == 2:
                return "{0:.3f}".format(node.data.time)
        return None

    def headerData(self, section, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return TreeModel.HEADERS[section]
        return None

class GuiCallback(QtCore.QObject):
    """Passed to TestExecutor for obtaining the current status of the tests
    and immediately updating the GUI. GUI updates are done in the GUI thread.
    """
    start = QtCore.pyqtSignal()
    start_all = QtCore.pyqtSignal()
    stop = QtCore.pyqtSignal()
    stop_all = QtCore.pyqtSignal()
    
    def __init__(self, tree_view, desc_widget, status_bar):
        QtCore.QObject.__init__(self)
        self._tree_view = tree_view
        self._desc_widget = desc_widget
        self._status_bar = status_bar
        
        self.start.connect(self._update_status_bar)
        self.stop.connect(self._update_data_views)
        self.stop_all.connect(self._update_status_bar)
        self._message = ""
        self._test = None
        
    def on_start_all(self):
        self.start_all.emit()
        
    def on_stop_all(self, should_stop, num_tests, num_success, num_skipped, num_failed, num_errors, num_unexp_success, num_exp_failures):
        if should_stop:
            self._message += "Execution interrupted! "
        self._message = "Ran " + str(num_tests) + " test"
        if num_tests != 1:
            self._message += "s"
        self._message += ": Passed " + str(num_success)
        self._message += ", Skipped " + str(num_skipped)
        self._message += ", Failures " + str(num_failed)
        self._message += ", Errors " + str(num_errors)
        if num_unexp_success > 0:
            self._message += ", Unexpectedly passed " + str(num_unexp_success)
        if num_exp_failures > 0:
            self._message += ", Expected failures " + str(num_exp_failures)
        
        self.stop_all.emit()
        
    def on_start(self, test):
        self._message = "Running " + str(test)
        self.start.emit()
    
    def on_stop(self, test):
        self._test = test
        self.stop.emit()
    
    def _update_status_bar(self):
        """Executes in the GUI thread."""
        self._status_bar.showMessage(self._message)
    
    def _update_data_views(self):
        """Executes in the GUI thread."""
        self._tree_view.dataChanged(QtCore.QModelIndex(), QtCore.QModelIndex())
        
        selected_test_item = self._tree_view.currentIndex().internalPointer().data
        s_tc_id = pyutf.get_test_item_id(selected_test_item)
        tc_id = pyutf.parse_test_case_id(self._test)
        
        if s_tc_id.is_superset_of(tc_id):
            self._desc_widget.currentWidget().update(selected_test_item)

class TestExecThreadObj(QtCore.QObject):
    """Just a dummy object for running TestExecutor in the background thread."""
    finished = QtCore.pyqtSignal()
    
    def __init__(self, test_executor):
        QtCore.QObject.__init__(self)
        self._test_executor = test_executor

    def do_run(self):
        self._test_executor.run()
        self.finished.emit()

class TestCaseDescWidget(QtGui.QWidget):
    """Widget for showing the details about the test case."""
    def __init__(self):
        super(TestCaseDescWidget, self).__init__()
        self._lbl_name = StyledLabel()
        self._lbl_name.setWordWrap(True)
        self._lbl_desc = StyledLabel()
        self._lbl_desc.setWordWrap(True)
        self._lbl_status = StyledLabel()
        self._lbl_time = StyledLabel()
        self._lbl_output = QtGui.QLabel()
        self._lbl_output.setWordWrap(True)
        self._lbl_output.setMargin(2)
        self._lbl_output.setAlignment(QtCore.Qt.AlignLeft)
        
        scroll_area = QtGui.QScrollArea()
        scroll_area.setFrameShape(QtGui.QFrame.StyledPanel)
        output_policy = scroll_area.sizePolicy()
        output_policy.setVerticalStretch(1)
        output_policy.setHorizontalStretch(0)
        scroll_area.setSizePolicy(output_policy)
        scroll_area.setAlignment(QtCore.Qt.AlignLeft)
        scroll_area.setWidget(self._lbl_output)
        scroll_area.setWidgetResizable(True)
        
        layout = QtGui.QFormLayout()
        layout.setLabelAlignment(QtCore.Qt.AlignRight)
        layout.addRow("Name:", self._lbl_name)
        layout.addRow("Description:", self._lbl_desc)
        layout.addRow("Status:", self._lbl_status)
        layout.addRow("Duration[s]:", self._lbl_time)
        layout.addRow("Output:", scroll_area)
        self.setLayout(layout)
    
    def update(self, test_item):
        self._lbl_name.setText(test_item.name)
        self._lbl_desc.setText(test_item.description)
        if test_item.status:
            self._lbl_status.setText(str(test_item.status))
        else:
            self._lbl_status.setText("")
        self._lbl_time.setText("{0:.3f}".format(test_item.time))
        
        output = test_item.output
        if output:
            if not output.endswith('\n'):
                output += '\n'
        output += test_item.outcome
        self._lbl_output.setText(output)

class TestSuiteDescWidget(QtGui.QWidget):
    """Widget for showing the details about the test suite."""
    def __init__(self):
        super(TestSuiteDescWidget, self).__init__()
        self._lbl_name = StyledLabel()
        self._lbl_name.setWordWrap(True)
        self._lbl_status = StyledLabel()
        self._lbl_status.setWordWrap(True)
        self._lbl_time = StyledLabel()
        self._lbl_num_tests = StyledLabel()
        self._lbl_num_passed = StyledLabel()
        self._lbl_num_skipped = StyledLabel()
        self._lbl_num_failed = StyledLabel()
        self._lbl_num_errors = StyledLabel()
        
        layout = QtGui.QFormLayout()
        layout.setLabelAlignment(QtCore.Qt.AlignRight)
        layout.addRow("Name:", self._lbl_name)
        layout.addRow("Status:", self._lbl_status)
        layout.addRow("Duration[s]:", self._lbl_time)
        layout.addRow("Tests:", self._lbl_num_tests)
        layout.addRow("Passed:", self._lbl_num_passed)
        layout.addRow("Skipped:", self._lbl_num_skipped)
        layout.addRow("Failed:", self._lbl_num_failed)
        layout.addRow("Errors:", self._lbl_num_errors)
        self.setLayout(layout)
    
    def update(self, test_item):
        self._lbl_name.setText(test_item.name)
        if test_item.status:
            self._lbl_status.setText(str(test_item.status))
        else:
            self._lbl_status.setText("")
        self._lbl_time.setText("{0:.3f}".format(test_item.time))
        
        num_tests, num_passed, num_skipped, num_failed, num_errors = pyutf.aggregate_results(test_item)
        self._lbl_num_tests.setText(str(num_tests))
        self._lbl_num_passed.setText(str(num_passed))
        self._lbl_num_skipped.setText(str(num_skipped))
        self._lbl_num_failed.setText(str(num_failed))
        self._lbl_num_errors.setText(str(num_errors))

class PyUTMainWindow(QtGui.QMainWindow):
    """Main window that contains the whole GUI."""
    def __init__(self):
        super(PyUTMainWindow, self).__init__()
        self._tests_configuration = None
        self._tests_path = "."
        
        self._ns_dialog = QtGui.QFileDialog(self)
        self._ns_dialog.setWindowTitle("Choose tests location")
        self._ns_dialog.setFileMode(QtGui.QFileDialog.Directory)
        self._ns_dialog.setViewMode(QtGui.QFileDialog.List)
        self._ns_dialog.setDirectory(".")

        self._act_new = QtGui.QAction("New", self)
        self._act_new.setShortcut('Ctrl+N')
        self._act_new.triggered.connect(self.new_session)
        
        self._act_save = QtGui.QAction("Save", self)
        self._act_save.setShortcut('Ctrl+S')
        self._act_save.triggered.connect(self.save_tests)
        
        act_exit = QtGui.QAction("Exit", self)
        act_exit.setShortcut('Ctrl+Q')
        act_exit.triggered.connect(QtGui.qApp.quit)
        
        menubar = self.menuBar()
        test_menu = menubar.addMenu("Test Session")
        test_menu.addAction(self._act_new)
        test_menu.addAction(self._act_save)
        test_menu.addSeparator()
        test_menu.addAction(act_exit)
        
        self.statusBar().showMessage("Ready")
        
        main_widget = QtGui.QWidget()
        self._test_executor = None
        self._test_exec_thread = None
        self._test_exec_obj = None
        self._exec_mutex = QtCore.QMutex()
        
        self._tree_view = QtGui.QTreeView()
        
        self._btn_run = QtGui.QPushButton("Run")
        self._btn_run.clicked.connect(self.run_tests)
        
        left_widget = QtGui.QWidget()
        wl_layout = QtGui.QVBoxLayout()
        wl_layout.addWidget(self._tree_view)
        wl_layout.addWidget(self._btn_run)
        left_widget.setLayout(wl_layout)
        
        tcase_widget = TestCaseDescWidget()
        tsuite_widget = TestSuiteDescWidget()

        self._desc_widget = QtGui.QStackedWidget()
        self._desc_widget.addWidget(tcase_widget)
        self._desc_widget.addWidget(tsuite_widget)
        
        layout = QtGui.QHBoxLayout()
        layout.addWidget(left_widget)
        layout.addWidget(self._desc_widget)
        layout.setMargin(0)
        main_widget.setLayout(layout)
        
        self._gui_callback = GuiCallback(self._tree_view, self._desc_widget, self.statusBar())
        
        self.load_tests()
        
        self.setCentralWidget(main_widget)
        self.setFixedSize(1000, 600)
        self.setWindowTitle("Tests GUI")
        self.center()
        self.show()
    
    def center(self):
        qr = self.frameGeometry()
        cp = QtGui.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
    
    def show_desc_widget(self):
        """Selects which widget to show in the GUI based on the selected test item."""
        test_item = self._tree_view.currentIndex().internalPointer().data
        if test_item.type == pyutf.TestItemType.FUNCTION:
            self._desc_widget.setCurrentIndex(0)
        else:
            self._desc_widget.setCurrentIndex(1)
        self._desc_widget.currentWidget().update(test_item)
    
    def new_session(self):
        if self._ns_dialog.exec_() == QtGui.QDialog.Accepted:
            self.load_tests(str(self._ns_dialog.selectedFiles()[0]))
        
    def load_tests(self, path="."):
        """Loads the tests and fills the tree view with them."""
        self._tests_path = path
        self._tests_configuration = pyutf.load_tests_configuration(path)
        root_test_item = pyutf.build_tests_tree(path, self._tests_configuration)
        self._tree_view.setModel(TreeModel([root_test_item]))
        self._tree_view.header().setStretchLastSection(False)
        self._tree_view.header().setResizeMode(0, QtGui.QHeaderView.Stretch)
        self._tree_view.expandAll()
        self._tree_view.selectionModel().selectionChanged.connect(self.show_desc_widget)
        
        # select the first element immediately
        root_index = self._tree_view.model().index(0, 0, QtCore.QModelIndex())
        self._tree_view.selectionModel().setCurrentIndex(root_index, QtGui.QItemSelectionModel.NoUpdate)
        self.show_desc_widget()
        
    def run_tests(self):
        """Creates background execution thread for running the tests or stops if it's already running."""
        with QtCore.QMutexLocker(self._exec_mutex):
            if not self._test_executor:
                self._btn_run.setText("Stop")
                self._act_new.setEnabled(False)
                self._act_save.setEnabled(False)
                
                test_item = self._tree_view.currentIndex().internalPointer().data
                self._test_executor = pyutf.TestExecutor(test_item, self._gui_callback)
                self._test_exec_thread = QtCore.QThread()
                self._test_exec_obj = TestExecThreadObj(self._test_executor)
                self._test_exec_obj.moveToThread(self._test_exec_thread)
                self._test_exec_obj.finished.connect(self._test_exec_thread.quit)
                self._test_exec_thread.started.connect(self._test_exec_obj.do_run)
                self._test_exec_thread.finished.connect(self._stop_tests_callback)
                self._test_exec_thread.start()
            else:
                self._test_executor.stop()
    
    def _stop_tests_callback(self):
        """Called automatically when the background execution thread is stopped."""
        with QtCore.QMutexLocker(self._exec_mutex):
            self._btn_run.setText("Run")
            self._act_new.setEnabled(True)
            self._act_save.setEnabled(True)
            
            self._test_executor = None
            self._test_exec_thread = None
            self._test_exec_obj = None

    def save_tests(self):
        """Saves the tests to the XML report file."""
        root_index = self._tree_view.model().index(0, 0, QtCore.QModelIndex())
        root_test_item = root_index.internalPointer().data
                
        _, np, ns, nf, ne = pyutf.aggregate_results(root_test_item)
        tests_run = np + ns + nf + ne
        if tests_run <= 0:
            msg_box = QtGui.QMessageBox()
            msg_box.setText("At least one test needs to be run to save the report.")
            msg_box.setIcon(QtGui.QMessageBox.Information)
            msg_box.exec_()
            return

        dt = datetime.now()
        dt = dt.replace(microsecond=0)
        default_file = "test-report-" + dt.strftime('%Y%m%dT%H%M%S') + ".xml"
        default_path = self._tests_path + "/" + default_file
                    
        filename = QtGui.QFileDialog.getSaveFileName(self, "Choose report location", default_path, "XML files (*.xml)")
        if filename:
            xml_report = pyutx.TestXmlReport()
            xml_report.save(filename, root_test_item, self._tests_configuration)

def main():
    app = QtGui.QApplication(sys.argv)
    _ = PyUTMainWindow()
    return app.exec_()
    
if __name__ == '__main__':
    sys.exit(main())
