import sys, configparser, time, MySQLdb, csv, os, platform

from PyQt5.QtWidgets import (QVBoxLayout, QLineEdit,QGridLayout,
 QApplication, QLabel, QMenu, QWidget, QHBoxLayout,QDialog,
 QAction, QTextEdit,QPushButton, qApp, QMessageBox, QInputDialog,
 QMainWindow, QFrame, QFileDialog, QCheckBox, QProgressBar,
 QListWidget, QCompleter, QComboBox, QTreeView,QAbstractItemView,
 QToolTip,QRadioButton,QButtonGroup)
from PyQt5.QtGui import (QIcon, QFont, QColor, QPixmap, QDrag, QPainter,
 QBrush, QPen,QStandardItem,QStandardItemModel,)
from PyQt5.QtCore import (QCoreApplication, Qt, QObject, pyqtSignal,
 QMimeData, QAbstractItemModel,QModelIndex)

from main_config import main_Config

class MyModel(QAbstractItemModel):


    def __init__(self, parent=None):
        super().__init__()

        self.headers = 'ラベル','一致', '同一カテゴリー','不一致'
        self.items = []

    def index(self, row, column, parent=QModelIndex()):
        return self.createIndex(row, column, None)

    def parent(self, child):
        return QModelIndex()

    def rowCount(self, parent=QModelIndex()):
        return len(self.items)

    def columnCount(self, parent=QModelIndex()):
        return len(self.headers)

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            try:
                return self.items[index.row()][index.column()]
            except:
                return
        return

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role != Qt.DisplayRole:
            return
        if orientation == Qt.Horizontal:
            return self.headers[section]

    def addRow(self, claster):
        self.beginInsertRows(QModelIndex(), len(self.items), 1)
        #self.items.insert(0,(labe, prediction, text))
        self.items.append((claster))
        self.endInsertRows()

    def remove_all(self):
        self.items.clear()

    def all_print(self):
        return self.items

class View(QTreeView):
    def __init__(self, parent=None):
        super(View, self).__init__(parent)
        self.setItemsExpandable(False)
        self.setIndentation(0)
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)

    def drawBranches(self, painter, rect, index):
        return

class Re_Labeling_Window(QWidget):
    def __init__(self, project):
        super().__init__()

        self.project=project

#        config=configparser.ConfigParser()
#        config.read('main.ini')
#        mysql_id=config['settings']["id"]
#        mysql_pass=config['settings']["pass"]
        mysql_id, mysql_pass, projects, root_path, using_os = main_Config()

        self.re_labeling_window()

        self.label_list(self.project, mysql_id, mysql_pass)

    def re_labeling_window(self):
        self.w=QDialog()

        self.model=MyModel(self)
        self.view=View()
        self.view.setModel(self.model)
        self.view.setUniformRowHeights(True)
        self.view.setColumnWidth(0, 150)
        self.view.setColumnWidth(1, 110)
        self.view.setColumnWidth(2, 110)
        self.view.setColumnWidth(3, 110)

        csv_h_box=QHBoxLayout()
        csv_push_button=QPushButton("csvで出力")
        close_button=QPushButton("閉じる")
        csv_h_box.addStretch(2)
        csv_h_box.addWidget(csv_push_button)
        csv_h_box.addWidget(close_button)
        close_button.clicked.connect(self.w.close)
        csv_push_button.clicked.connect(self.make_csv)

        main_layout=QVBoxLayout()
        main_layout.addWidget(self.view)
        main_layout.addLayout(csv_h_box)

        self.w.setGeometry(700, 300, 500, 400)
        self.w.setWindowTitle('細分類の結果')

        self.w.setLayout(main_layout)

    def count_my_sql(self, project, mysql_id, mysql_pass, label, disc_code):
        try:
            conn=MySQLdb.connect(db=project, user=mysql_id, passwd=mysql_pass, charset="utf8mb4")
            cursor=conn.cursor()

            sql="select count(*) from text_table where label_name = '" + label + "' and disc_code = " + str(disc_code)

            cursor.execute(sql)
            time.sleep(0.1)

            counts=list(cursor.fetchall())

            conn.commit()
            cursor.close()
            conn.close()

            res=(counts[0])[0]

            return res

        except Exception as e:
            print(e)

    def label_list(self, project, mysql_id, mysql_pass):
        try:
            conn=MySQLdb.connect(db=project, user=mysql_id, passwd=mysql_pass, charset="utf8mb4")
            cursor=conn.cursor()

            sql="select label_name, count(*) from text_table group by label_name"

            cursor.execute(sql)
            time.sleep(0.1)

            counts=list(cursor.fetchall())

            conn.commit()
            cursor.close()
            conn.close()

            labels=[]
            for n in counts:
                labels.append(n[0])

            result_list=[]
            for label in labels:
                result=[]
                result.append(label.replace("'",""))
                for n in range(1, 4):
                    res = self.count_my_sql(project, mysql_id, mysql_pass, label, n)
                    result.append(res)
                    #self.model.addRow(a)
                #result_list.append(tuple(result))
                self.model.addRow(tuple(result))
            #(result_list)

        except Exception as e:
            print(e)

    def make_csv(self):
        header = tuple(self.model.headers)
        content = self.model.items
        #print(header)
        #print(content)
        alls=[]
        alls.append(header)
        alls.extend(content)
        #print(alls)

        if len(content) == 0:
            #print("保存するデータがありません")
            message=QMessageBox.information(self,"お知らせ",  "保存するデータがありません", QMessageBox.Ok)
        else:
            try:
                now_folder = os.getcwd()
                ########################################################
                frame=QFileDialog.getSaveFileName(self, "保存フォルダーの選択", now_folder,filter=("csv files(*.csv)"))
                ########################################################
                save_file_path = frame[0]# + ".csv"

                if platform.system() == "Darwin" or os.name == "nt":
                    f = open(save_file_path, "w", encoding='utf-16')
                    write = csv.writer(f, dialect='excel-tab', lineterminator='\n')
                    write.writerows(alls)
                    f.close()
                else:
                    f = open(save_file_path, "w")
                    write = csv.writer(f, lineterminator='\n')
                    write.writerows(alls)
                    f.close()
            except Exception as e:
                print(e)

    def show(self):
        self.w.exec_()

if __name__=="__main__":
    app=QApplication(sys.argv)
    project="ok"
    Re_Labeling_Window(project).show()
    sys.exit(app.exec_())
