#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, logging, sys
from PyQt5 import QtCore, QtGui, QtWidgets
import empires
import empires_ui
from single_empire import EmpireTab

class TabBar(QtWidgets.QTabBar):
    ''' http://stackoverflow.com/questions/9442165/pyqt-mouse-events-for-qtabwidget
    example usage:
        self.tabBar = TabBar()
        self.tabWidget.setTabBar(self.tabBar)
        self.tabBar.middleClicked.connect(self.onTabMiddleClick)
    '''
    middleClicked = QtCore.pyqtSignal(int)
    def __init__(self):
        super(QtWidgets.QTabBar, self).__init__()
        self.previousMiddleIndex = -1
    def mousePressEvent(self, mouseEvent):
        if mouseEvent.button() == QtCore.Qt.MidButton:
            self.previousIndex = self.tabAt(mouseEvent.pos())
        QtWidgets.QTabBar.mousePressEvent(self, mouseEvent)
    def mouseReleaseEvent(self, mouseEvent):
        if mouseEvent.button() == QtCore.Qt.MidButton and \
            self.previousIndex == self.tabAt(mouseEvent.pos()):
            self.middleClicked.emit(self.previousIndex)
        self.previousIndex = -1
        QtWidgets.QTabBar.mouseReleaseEvent(self, mouseEvent)

class QEmpiresSettings:
    @classmethod
    def initialize(cls):
        cls.icon_view = QtGui.QIcon(QtGui.QPixmap("./img/view-process-own.png"))

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = empires_ui.Ui_MainWindow()
        
        
        self.ui.setupUi(self)
        
        self.tabBar = TabBar()
        self.tabBar.addTab('Empires')
        self.ui.tabWidget.setTabBar(self.tabBar)
        
        
        self.tabBar.middleClicked.connect(self.onTabMiddleClick)
        self.user_empires = None
        self.load_empires(None)
    
    def onTabMiddleClick(self, index):
        if index == 0:
            return
        else:
            self.ui.tabWidget.removeTab(index)
            #self.tabBar.removeTab(index)
    
    def get_empire_tab(self, empire):
        # this either creates a tab or gets the appropriate tabWidget entry.
        for x in range(1, self.ui.tabWidget.count()):
            widget = self.ui.tabWidget.widget(x)
            e = getattr(widget, 'empire', None)
            if e is not None and e == empire:
                return widget 
        empire_tab = EmpireTab(empire)
        self.ui.tabWidget.addTab(empire_tab, empire.name)
        empire_tab.empire = empire
        return empire_tab
    
    def edit_empire(self, empire=None):
        try:
            # print(f"Empire is {empire}") # for some reason qt5 sends a boolean.
            if not empire:
                sender = self.sender()
                empire = getattr(sender, 'empire', None)
                if not empire:
                    logging.error("No Empire in Button Sender!???")
                    return
            # open a new tab for this empire.
            empire_tab = self.get_empire_tab(empire)
            i = self.ui.tabWidget.indexOf(empire_tab)
            if (i >= 0):
                self.ui.tabWidget.setCurrentIndex(i)
        except:
            import traceback
            traceback.print_exc()
            return
            
    def clear_table(self):
        while (self.ui.tableWidget.rowCount() > 0):
            self.ui.tableWidget.removeRow(0)
    
    def fill_empires(self, empires):
        self.clear_table()
        for empire in empires:
            table = self.ui.tableWidget
            rowPosition = table.rowCount()
            table.insertRow(rowPosition)
            empire_buttons = QtWidgets.QWidget()
            button_edit = QtWidgets.QPushButton(QEmpiresSettings.icon_view, "", empire_buttons)
            button_edit.empire = empire
            button_edit.clicked.connect( self.edit_empire )
            """
            QWidget* pWidget = new QWidget();
            QPushButton* btn_edit = new QPushButton();
            btn_edit->setText("Edit");
            QHBoxLayout* pLayout = new QHBoxLayout(pWidget);
            pLayout->addWidget(btn_edit);
            pLayout->setAlignment(Qt::AlignCenter);
            pLayout->setContentsMargins(0, 0, 0, 0);
            pWidget->setLayout(pLayout);
            ui.table->setCellWidget(i, 3, pWidget);
            """
            table.setCellWidget(rowPosition, 0, empire_buttons)         
            #table.setItem(rowPosition , 0, empire_buttons)
            table.setItem(rowPosition , 1, QtWidgets.QTableWidgetItem(empire.name))
            table.setItem(rowPosition , 2, QtWidgets.QTableWidgetItem(', '.join([ x.replace('trait_', '').replace('_', ' ') for x in empire.get_values('trait', [])])))
            table.setItem(rowPosition , 3, QtWidgets.QTableWidgetItem(', '.join([ x.replace('ethic_', '').replace('_', ' ') for x in empire.get_values('ethic', [])])))
            table.setItem(rowPosition , 4, QtWidgets.QTableWidgetItem(''.join([ ', '.join([y.replace('civic_', '').replace('_', ' ') for y in x]) for x in empire.get_values('civics', [])])))
            table.setItem(rowPosition , 5, QtWidgets.QTableWidgetItem('%s (%s)' % (empire.get_values('planet_name', ['?'])[0],
                                                                        empire.get_values('system_name', ['?'])[0])))
            table.setItem(rowPosition, 6, QtWidgets.QTableWidgetItem('%s' % (empire.get_values('species_bio', [''])[0])))
            
            # set header.
            header = table.horizontalHeader()
            header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
            header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
            header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
            header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
            header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
            header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents)
            header.setSectionResizeMode(6, QtWidgets.QHeaderView.Stretch)
            
    
    def load_empires(self, filename):
        try:
            self.user_empires = empires.load_empires(filename)
        except:
            import traceback
            traceback.print_exc()
            logging.error("File %s could not be loaded." % filename)
            return
        self.fill_empires(self.user_empires.all())
            

###################################################
def _main():
    app = QtWidgets.QApplication(sys.argv)
    QEmpiresSettings.initialize()
    window = MainWindow()
    #window.resize(640, 480)
    window.show()
    return app.exec_()

def main():
    r = _main()
    try:
        import psutil #@UnresolvedImport
    except ImportError:
        logging.warning('Cannot import PsUtil, terminating without cleaning up threads explicitly.')
        sys.exit(r)
        
    def kill_proc_tree(pid, including_parent=True):    
        parent = psutil.Process(pid)
        if including_parent:
            parent.kill()
    me = os.getpid()
    kill_proc_tree(me)
    sys.exit(r)

if __name__ == "__main__":
    main()
    