import time, sys, configparser, 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 PyQt5 import QtCore

from search_main_word import search_main_word
from main_config import main_Config


class MyModel(QAbstractItemModel):
    headers = 'クラスター番号', 'クラスター件数', 'メインワード', 'メインワード件数', 'サブワード', 'サブワード件数'
    items = []

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


    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

    def removeRows(self, rowIndexes):
        del self.items[rowIndexes]
#        for row in sorted(rowIndexes, reverse=True):
#            self.beginRemoveRows(QModelIndex(), row, row + 1)
#            #print(self.items[row])
#            del self.items[row]
#            self.endRemoveRows()

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 Confirm_Window(QWidget):
    def __init__(self, project, claster_count):
        super(Confirm_Window, self).__init__()

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

        MyModel.items.clear()

        self.project = project
        self.claster_count = int(claster_count)
        self.selected_main_claster = "0"

        self.confirm_window()
        self.add_combo_box()
        #self.count_claster(self.project,self.mysql_id,self.mysql_pass,"0")

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

        select_claster_h_box=QHBoxLayout()
        select_claster_label=QLabel("確認するクラスター番号")
        self.select_claster=QComboBox(self)
        self.count=QLabel()

        self.select_claster.activated[str].connect(self.selected_claster)

        radio_h_box = QHBoxLayout()
        self.content_word = QRadioButton("内容語") #基本形を使用
        self.all_word = QRadioButton("全出現語")  #表層形を使用
        self.content_word.toggle()
        self.button_group = QButtonGroup()
        self.button_group.addButton(self.content_word)
        self.button_group.addButton(self.all_word)
        radio_h_box.addWidget(self.content_word)
        radio_h_box.addWidget(self.all_word)
        radio_h_box.addStretch(1)

        search_h_box=QHBoxLayout()
        search_button=QPushButton("検索")
        search_button.clicked.connect(self.search)
        search_h_box.addWidget(search_button)
        search_h_box.addStretch(1)

        select_claster_h_box.addWidget(select_claster_label)
        select_claster_h_box.addStretch(1)
        select_claster_h_box.addWidget(self.select_claster)
        #select_claster_h_box.addStretch(1)
        select_claster_h_box.addWidget(self.count)
        select_claster_h_box.addStretch(1)
        select_claster_h_box.addLayout(radio_h_box)
        select_claster_h_box.addStretch(1)
        select_claster_h_box.addLayout(search_h_box)

        frequent_h_box=QHBoxLayout()

        frequent_v_box=QVBoxLayout()
        main_label=QLabel("クラスター内の頻出語")
        self.main_frequent=QListWidget()
        #self.main_frequent.setSelectionMode(QAbstractItemView.ExtendedSelection)
        frequent_v_box.addWidget(main_label)
        frequent_v_box.addWidget(self.main_frequent)
##########################################################################################
        word_a_h_box=QHBoxLayout()

        to_from_a_box=QVBoxLayout()
        to_word_a_button=QPushButton(">")
        to_word_a_button.clicked.connect(lambda: self.to_word(self.main_frequent, self.word_a_list, self.word_a_label))
        from_word_a_button=QPushButton("<")
        from_word_a_button.clicked.connect(lambda: self.from_word(self.main_frequent, self.word_a_list, self.word_a_label))
        to_from_a_box.addStretch(1)
        to_from_a_box.addWidget(to_word_a_button)
        to_from_a_box.addWidget(from_word_a_button)
        to_from_a_box.addStretch(1)

        word_a_v_box=QVBoxLayout()
        null_word_label_a=QLabel()
        self.word_a_label=QLabel()
        self.word_a_list=QListWidget()
        self.word_a_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        word_a_v_box.addWidget(null_word_label_a)
        word_a_v_box.addWidget(self.word_a_label)
        word_a_v_box.addWidget(self.word_a_list)

        sub_to_from_a_box=QVBoxLayout()
        sub_to_word_a_button=QPushButton(">")
        sub_to_word_a_button.clicked.connect(lambda: self.sub_to_word(self.word_a_list, self.sub_word_a_list, self.sub_word_a_label, self.word_a_label))
        sub_from_word_a_button=QPushButton("<")
        sub_from_word_a_button.clicked.connect(lambda: self.sub_from_word(self.word_a_list, self.sub_word_a_list, self.sub_word_a_label, self.word_a_label))
        sub_to_from_a_box.addStretch(1)
        sub_to_from_a_box.addWidget(sub_to_word_a_button)
        sub_to_from_a_box.addWidget(sub_from_word_a_button)
        sub_to_from_a_box.addStretch(1)

        sub_word_a_v_box=QVBoxLayout()
        sub_null_word_label_a=QLabel()
        self.sub_word_a_label=QLabel()
        self.sub_word_a_list=QListWidget()
        sub_word_a_v_box.addWidget(sub_null_word_label_a)
        sub_word_a_v_box.addWidget(self.sub_word_a_label)
        sub_word_a_v_box.addWidget(self.sub_word_a_list)

        word_a_h_box.addLayout(to_from_a_box)
        word_a_h_box.addLayout(word_a_v_box)
        word_a_h_box.addLayout(sub_to_from_a_box)
        word_a_h_box.addLayout(sub_word_a_v_box)
##########################################################################################
        word_b_h_box=QHBoxLayout()

        to_from_b_box=QVBoxLayout()
        to_word_b_button=QPushButton(">")
        to_word_b_button.clicked.connect(lambda: self.to_word(self.main_frequent, self.word_b_list, self.word_b_label))
        from_word_b_button=QPushButton("<")
        from_word_b_button.clicked.connect(lambda: self.from_word(self.main_frequent, self.word_b_list, self.word_b_label))
        to_from_b_box.addStretch(1)
        to_from_b_box.addWidget(to_word_b_button)
        to_from_b_box.addWidget(from_word_b_button)
        to_from_b_box.addStretch(1)

        word_b_v_box=QVBoxLayout()
        self.word_b_label=QLabel()
        self.word_b_list=QListWidget()
        self.word_b_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        word_b_v_box.addWidget(self.word_b_label)
        word_b_v_box.addWidget(self.word_b_list)

        sub_to_from_b_box=QVBoxLayout()
        sub_to_word_b_button=QPushButton(">")
        sub_to_word_b_button.clicked.connect(lambda: self.sub_to_word(self.word_b_list, self.sub_word_b_list, self.sub_word_b_label, self.word_b_label))
        sub_from_word_b_button=QPushButton("<")
        sub_from_word_b_button.clicked.connect(lambda: self.sub_from_word(self.word_b_list, self.sub_word_b_list, self.sub_word_b_label, self.word_b_label))
        sub_to_from_b_box.addStretch(1)
        sub_to_from_b_box.addWidget(sub_to_word_b_button)
        sub_to_from_b_box.addWidget(sub_from_word_b_button)
        sub_to_from_b_box.addStretch(1)

        sub_word_b_v_box=QVBoxLayout()
        #sub_null_word_label_a=QLabel()
        self.sub_word_b_label=QLabel()
        self.sub_word_b_list=QListWidget()
        #sub_word_b_v_box.addWidget(sub_null_word_label_b)
        sub_word_b_v_box.addWidget(self.sub_word_b_label)
        sub_word_b_v_box.addWidget(self.sub_word_b_list)

        word_b_h_box.addLayout(to_from_b_box)
        word_b_h_box.addLayout(word_b_v_box)
        word_b_h_box.addLayout(sub_to_from_b_box)
        word_b_h_box.addLayout(sub_word_b_v_box)
##########################################################################################
        word_c_h_box=QHBoxLayout()

        to_from_c_box=QVBoxLayout()
        to_word_c_button=QPushButton(">")
        to_word_c_button.clicked.connect(lambda: self.to_word(self.main_frequent, self.word_c_list, self.word_c_label))
        from_word_c_button=QPushButton("<")
        from_word_c_button.clicked.connect(lambda: self.from_word(self.main_frequent, self.word_c_list, self.word_c_label))
        to_from_c_box.addStretch(1)
        to_from_c_box.addWidget(to_word_c_button)
        to_from_c_box.addWidget(from_word_c_button)
        to_from_c_box.addStretch(1)

        word_c_v_box=QVBoxLayout()
        self.word_c_label=QLabel()
        self.word_c_list=QListWidget()
        self.word_c_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        word_c_v_box.addWidget(self.word_c_label)
        word_c_v_box.addWidget(self.word_c_list)

        sub_to_from_c_box=QVBoxLayout()
        sub_to_word_c_button=QPushButton(">")
        sub_to_word_c_button.clicked.connect(lambda: self.sub_to_word(self.word_c_list, self.sub_word_c_list, self.sub_word_c_label, self.word_c_label))
        sub_from_word_c_button=QPushButton("<")
        sub_from_word_c_button.clicked.connect(lambda: self.sub_from_word(self.word_c_list, self.sub_word_c_list, self.sub_word_c_label, self.word_c_label))
        sub_to_from_c_box.addStretch(1)
        sub_to_from_c_box.addWidget(sub_to_word_c_button)
        sub_to_from_c_box.addWidget(sub_from_word_c_button)
        sub_to_from_c_box.addStretch(1)

        sub_word_c_v_box=QVBoxLayout()
        #sub_null_word_label_a=QLabel()
        self.sub_word_c_label=QLabel()
        self.sub_word_c_list=QListWidget()
        #sub_word_b_v_box.addWidget(sub_null_word_label_b)
        sub_word_c_v_box.addWidget(self.sub_word_c_label)
        sub_word_c_v_box.addWidget(self.sub_word_c_list)

        word_c_h_box.addLayout(to_from_c_box)
        word_c_h_box.addLayout(word_c_v_box)
        word_c_h_box.addLayout(sub_to_from_c_box)
        word_c_h_box.addLayout(sub_word_c_v_box)
##########################################################################################

        add_sheet=QHBoxLayout()
        add_button=QPushButton("シートに追加")
        add_sheet.addStretch(1)
        add_sheet.addWidget(add_button)
        add_button.clicked.connect(self.add_sheet_func)

        frequent_sub_box=QVBoxLayout()
        frequent_sub_box.addLayout(word_a_h_box)
        frequent_sub_box.addLayout(word_b_h_box)
        frequent_sub_box.addLayout(word_c_h_box)

        frequent_h_box.addLayout(frequent_v_box)
        frequent_h_box.addLayout(frequent_sub_box)

        self.model=MyModel(self)
        self.view=View()
        self.view.setModel(self.model)
        self.view.setUniformRowHeights(True)
        self.view.setColumnWidth(0, 145)
        self.view.setColumnWidth(1, 145)
        self.view.setColumnWidth(2, 145)
        self.view.setColumnWidth(3, 145)
        self.view.setColumnWidth(4, 145)
        self.view.setColumnWidth(5, 145)

        for_csv_h_box=QHBoxLayout()
        for_csv=QPushButton("csvファイルの作成")
        for_csv.clicked.connect(self.export_csv)
        for_csv_h_box.addStretch(1)
        for_csv_h_box.addWidget(for_csv)
        close_button=QPushButton("閉じる")
        close_button.clicked.connect(self.close_window)
        for_csv_h_box.addWidget(close_button)

        main_layout=QVBoxLayout()
        main_layout.addLayout(select_claster_h_box)
        main_layout.addStretch(1)
        main_layout.addLayout(frequent_h_box)
        main_layout.addLayout(add_sheet)
        main_layout.addWidget(self.view)
        main_layout.addLayout(for_csv_h_box)

        self.w.setGeometry(900, 200, 900, 900)
        self.w.setWindowTitle('各クラスターの内容の確認')

        self.w.setLayout(main_layout)

    def export_csv(self):
        alls = self.model.all_print()

        head=self.model.headers
        alls.insert(0,head)

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

                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 add_sheet_func(self):
        items = []
        a_items=[]
        b_items=[]
        c_items=[]
        for index in range(self.sub_word_a_list.count()):
            a_items.append(self.sub_word_a_list.item(index).text())
        for index in range(self.sub_word_b_list.count()):
            b_items.append(self.sub_word_b_list.item(index).text())
        for index in range(self.sub_word_c_list.count()):
            c_items.append(self.sub_word_c_list.item(index).text())

        for n in a_items:
            n = n.split("  ")
            sub_word=n[0]
            sub_count=n[1].replace("(","").replace(")","")
            claster_name = "クラスター" + self.selected_main_claster
            claster_count = (self.count.text().split(" "))[1]
            main_worda=self.word_a_label.text().split("  ")
            main_word=main_worda[0]
            main_count=main_worda[1].replace("(","").replace(")","")
            a=(claster_name, claster_count, main_word, main_count, sub_word, sub_count)
            self.model.addRow(a)

        for n in b_items:
            n = n.split("  ")
            sub_word=n[0]
            sub_count=n[1].replace("(","").replace(")","")
            claster_name = "クラスター" + self.selected_main_claster
            claster_count = (self.count.text().split(" "))[1]
            main_worda=self.word_b_label.text().split("  ")
            main_word=main_worda[0]
            main_count=main_worda[1].replace("(","").replace(")","")
            a=(claster_name, claster_count, main_word, main_count, sub_word, sub_count)
            self.model.addRow(a)

        for n in c_items:
            n = n.split("  ")
            sub_word=n[0]
            sub_count=n[1].replace("(","").replace(")","")
            claster_name = "クラスター" + self.selected_main_claster
            claster_count = (self.count.text().split(" "))[1]
            main_worda=self.word_c_label.text().split("  ")
            main_word=main_worda[0]
            main_count=main_worda[1].replace("(","").replace(")","")
            a=(claster_name, claster_count, main_word, main_count, sub_word, sub_count)
            self.model.addRow(a)

        self.main_frequent.clear()
        self.word_a_list.clear()
        self.word_b_list.clear()
        self.word_c_list.clear()
        self.sub_word_a_list.clear()
        self.sub_word_b_list.clear()
        self.sub_word_c_list.clear()
        self.word_a_label.setText("")
        self.word_b_label.setText("")
        self.word_c_label.setText("")

    def sub_to_word(self, sub, sub_sub, sub_label, main_label):
        for n in sub.selectedItems():
            selected_word = n.text()
            sub_sub.addItem(selected_word)
            sub.takeItem(sub.currentRow())

    def sub_from_word(self, sub, sub_sub, sub_label, main_label):
        for n in sub_sub.selectedItems():
            selected_word = n.text()
            sub.insertItem(0,selected_word)
            sub_sub.takeItem(sub_sub.currentRow())

    def to_word(self, main, sub, label):
        selected_word=""

        if label.text() != "":
            main.insertItem(0, label.text())
            sub.clear()
        else:
            pass

        for n in main.selectedItems():
            selected_word = n.text()

        if selected_word == "":
            pass
        else:
            label.setText(selected_word)
            main.takeItem(main.currentRow())
            func=1
            word=(selected_word.split(" "))[0]
            sub_word_list = search_main_word(self. project, self. mysql_id, self.mysql_pass, self.selected_main_claster, self.content_word_check, func, word)

            for n in sub_word_list:
                word = n[0]
                count = n[1]
                n = word + "  (" + str(count) + ")"
                if n == selected_word:
                    pass
                else:
                    sub.addItem(n)

    def from_word(self, main, sub, label):
        if label.text() != "":
            main.insertItem(0, label.text())
            label.setText("")
            sub.clear()
        else:
            pass


    def search(self):
        if self.content_word.isChecked() == True:
            self.content_word_check=0    #基本形
        else:
            self.content_word_check=1    #表層形
        func=0  #mainのリスト抽出
        word="" #sub読み出し用
        main_word_list = search_main_word(self. project, self. mysql_id, self.mysql_pass, self.selected_main_claster, self.content_word_check, func, word)

        self.count_claster(self.project,self.mysql_id,self.mysql_pass, self.selected_main_claster)

        for n in main_word_list:
            word = n[0]
            count = n[1]
            n = word + "  (" + str(count) + ")"
            self.main_frequent.addItem(n)

    def selected_claster(self, text):
        self.selected_main_claster=text.replace("クラスター","")

        self.main_frequent.clear()
        self.word_a_list.clear()
        self.word_b_list.clear()
        self.word_c_list.clear()
        self.sub_word_a_list.clear()
        self.sub_word_b_list.clear()
        self.sub_word_c_list.clear()
        self.word_a_label.setText("")
        self.word_b_label.setText("")
        self.word_c_label.setText("")

        self.count.setText("")

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

            sql="select count(*) from text_table where k_means_label = " + claster
            cursor.execute(sql)
            count=list(cursor.fetchall())
            time.sleep(0.1)

            count =(count[0])[0]

            conn.commit()
            cursor.close()
            conn.close()
            time.sleep(0.1)

            a = "クラスター内の文章数: " + str(count)
            self.count.setText(a)

        except Exception as e:
            print(e)


    def add_combo_box(self):
        for n in range(self.claster_count):
            items = "クラスター" + str(n)
            self.select_claster.addItem(items)

    def close_window(self):
        self.w.close()

    def closeEvent(self, event):
        print("a")
        #self.model.remove_all()
        self.w.close()

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

if __name__=="__main__":
    app=QApplication(sys.argv)
    project="tttt"
    clacter_count="3"
    Confirm_Window(project,clacter_count).show()
    sys.exit(app.exec_())
