import os
import time
import traceback
from datetime import datetime
from pathlib import Path

from PySide2 import QtCore
from PySide2.QtCore import QFile, QThread, Qt
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QDialog, QListWidgetItem, QWidget, QCheckBox, QLabel, QHBoxLayout, QApplication
from axipy import data_manager, QueryTable, SelectionTable, provider_manager, Notifications

from deleteDouble.ui.tools.processDelDouble import DelDoubleRow


class DlgDoubleRow(QDialog):
    cancelProcess = QtCore.Signal()
    def __init__(self,parent=None):
        super().__init__(parent)
        self.__parentWin=parent
        self.load_ui('DlgDeleteDoubleV2.ui')
        self.ui.cmb_tables.currentIndexChanged.connect(self.__changeTable)
        self.ui.ch_selectAll.stateChanged.connect(self.__selectAll)
        self.ui.ch_style.stateChanged.connect(self.__isEnableRun)
        self.ui.ch_geometry.stateChanged.connect(self.__isEnableRun)
        self.__tableList()
        #self.ui.pb_cancel.setEnabled(False)
        self.ui.pb_run.clicked.connect(self.__run_bt)
        self.ui.pb_cancel.clicked.connect(self.__cancel)
        self.ui.setWindowFlag(Qt.WindowContextHelpButtonHint, False)
        self.ui.setWindowFlag(Qt.WindowCloseButtonHint ,False)
        self.__process=None

    def load_ui(self, name_resource):
        loader = QUiLoader()
        path = os.path.join(os.path.dirname(__file__), name_resource)
        ui_file = QFile(path)
        ui_file.open(QFile.ReadOnly)
        self.ui = loader.load(ui_file, self.__parentWin)
        ui_file.close()
    def __tableList(self):
        self.ui.cmb_tables.clear()
        for table in data_manager.tables:
            if isinstance(table,QueryTable) or isinstance(table,SelectionTable):
                continue
            if table.is_spatial and table.is_editable and (not table.is_temporary):
                self.ui.cmb_tables.addItem(table.name)
        self.ui.cmb_tables.setCurrentIndex(0)
    def __changeTable(self,index):
        name_tab=self.ui.cmb_tables.currentText()
        tab_sel=data_manager.find(name_tab)
        self.__initListFieldWidget(tab_sel)
        #self.ui.pb_run.setEnabled(True)
        self.ui.ch_selectAll.setChecked(True)
    def __initListFieldWidget(self,table):
        self.ui.list_fields_widget.clear()
        for att_name in table.schema.attribute_names:
            item, item_widget = self.__createItemFields(att_name,True)
            self.ui.list_fields_widget.addItem(item)
            self.ui.list_fields_widget.setItemWidget(item, item_widget)
    def __createItemFieldsZZZ(self,name,isSelect=True):
        item = QListWidgetItem()
        #item_widget = QWidget()
        line_chekBox = QCheckBox()
        if isSelect:
            line_chekBox.setChecked(True)
        line_chekBox.setObjectName(name)
        line_chekBox.setText(name)
        # line_chekBox.setCheckState(True)
        #line_text = QLabel(name)
        #item_layout = QHBoxLayout()
        #item_layout.addWidget(line_chekBox)
        #item_layout.addWidget(line_text)
        #item_widget.setLayout(item_layout)
        #item.setSizeHint(item_widget.sizeHint())
        item.setWhatsThis(name)
        #return item,item_widget
    def __createItemFields(self,name,isSelect=True):
        item = QListWidgetItem()
        item_widget = QWidget()
        line_chekBox = QCheckBox()
        if isSelect:
            line_chekBox.setChecked(True)
        line_chekBox.stateChanged.connect(self.__isEnableRun)
        line_chekBox.setObjectName(name)
        line_chekBox.setText(name)
        # line_chekBox.setCheckState(True)
        #line_text = QLabel(name)
        item_layout = QHBoxLayout()
        item_layout.addWidget(line_chekBox)
        #item_layout.addWidget(line_text)
        item_widget.setLayout(item_layout)
        item.setSizeHint(item_widget.sizeHint())
        item.setWhatsThis(name)
        return item,item_widget
    def __selectAll(self):
        isAll=self.ui.ch_selectAll.isChecked()
        self.__updateCheckedStatusAtt(isAll)
        self.__isEnableRun()
    def __updateCheckedStatusAtt(self,statusChecked):
        count_fields=self.ui.list_fields_widget.count()
        for i in range(count_fields):
            item_widget = self.ui.list_fields_widget.item(i)
            name = item_widget.whatsThis()
            check_box = self.ui.findChild(QCheckBox, name)
            check_box.setChecked(statusChecked)

    def __isEnableRun(self):
        if self.ui.ch_style.isChecked() or self.ui.ch_geometry.isChecked():
            self.ui.pb_run.setEnabled(True)
            return
        count_sel_fields=len(self.__getListSelectFields())
        if count_sel_fields>0:
            self.ui.pb_run.setEnabled(True)
            return
        self.ui.pb_run.setEnabled(False)

    def __getListSelectFields(self):
        sel_fields=[]
        count_fields = self.ui.list_fields_widget.count()
        for i in range(count_fields):
            item_widget = self.ui.list_fields_widget.item(i)
            name = item_widget.whatsThis()
            check_box = self.ui.findChild(QCheckBox, name)
            if check_box.isChecked():
                sel_fields.append(name)
        return sel_fields
    '''
    def __cancel(self):
        if self.__process is not None:
            self.__process_status = False
            self.cancelProcess.emit()
            self.__process.setCancel()
        else:
            self.ui.close()
    '''
    def __update_progress(self, value_main):

        self.ui.prog_bar.setValue(value_main)

        # print(value)
        time.sleep(0.0001)
        QApplication.processEvents()
    def __cancel(self):
        if self.__process is not None:
            self.__process_status = False
            self.cancelProcess.emit()
            self.__process.setCancel()
        else:
            self.ui.close()
    def __setFormatprogressBar(self, str_format_main):
        if str_format_main is not None and len(str_format_main)>0:
            self.ui.prog_bar.setFormat(str_format_main)


        import time
        time.sleep(0.0001)
        QApplication.processEvents()
    def __end_process(self, value):
        if self.thread is not None:
            self.thread.quit()
            self.thread.running = False
            self.thread.wait(500)
        self.ui.prog_bar.setValue(value)
        self.ui.pb_run.setEnabled(True)
        self.ui.pb_cancel.setText("Закрыть")
        #self.ui.pb_cancel.setEnabled(False)
        #self.__process.updateProcess.disconnect()
        #self.__process.finished.disconnect()
        #self.__process.disconnect(self.__end_process)
        if self.__process is not None:
            if not self.__process.IsCancel:
                path_result_file=self.__process.PathResultFile
                table_res=provider_manager.openfile(path_result_file)
                Notifications.push('Удаление дублей', "Открыта таблицы "+table_res.name, Notifications.Information)
        self.__process=None
        self.thread=None
        print("end")
    def close(self):
        self.ui.close()
    def __run_bt(self):
        try:
            self.__run()
        except:
            traceback.print_exc()
            self.ui.close()
    def __run(self):

        self.ui.pb_run.setEnabled(False)
        self.ui.pb_cancel.setText("Прервать")
        self.ui.pb_cancel.setEnabled(True)

        if self.__process is None:
            self.__process = DelDoubleRow(self)

        else:
            try:
                self.__process.disconnect(self.__update_progress)
            except:
                pass
        self.__process.updateProcess.connect(self.__update_progress)
        self.__process.finished.connect(self.__end_process)
        params={}
        list_select_fields=self.__getListSelectFields()
        if self.ui.ch_style.isChecked():
            list_select_fields.append('style')
        if self.ui.ch_geometry.isChecked():
            list_select_fields.append('obj')
        params['list_fields']=list_select_fields
        params['table']=self.ui.cmb_tables.currentText()
        table_src = data_manager.find(self.ui.cmb_tables.currentText())
        path_source_tab=table_src.properties['fileName']
        path_folder=str(Path(path_source_tab).parent)
        name_file=str(Path(path_source_tab).stem)
        new_file=name_file+"_"+datetime.now().strftime('%Y_%m_%d_%H_%M_%S')+".tab"
        params['file_dest']=str(Path(path_folder).joinpath(new_file))
        self.__process.setParametrs(params)
        #self.__process.updateFormatProgressBar.connect(self.__setFormatprogressBar)
        #self.__process.finished.connect(self.__end_process)


        self.thread = QThread()
        #self.thread.started.connect(self.__process.run)
        self.__process.moveToThread(self.thread)
        self.thread.started.connect(self.__process.run)
        self.__process.updateProcess.connect(self.__update_progress)
        self.__process.updateFormatProgressBar.connect(self.__setFormatprogressBar)
        self.__process.finished.connect(self.__process.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)
        self.__process.finished.connect(self.thread.quit)
        self.__process.finished.connect(self.__end_process)
        self.__process.run()
        #self.__process.start()
        #self.thread.start()


    @property
    def widget(self):
        return self.ui


    def show(self):
        # self.ui.showMaximized()
        # print("Show Form")
        self.ui.show()