import sys, configparser, time, os

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,
 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 word_count_window import Word_Count
from similar_word_calcuration import Similar_word_Calcuration

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, labe, count):
        self.beginInsertRows(QModelIndex(), len(self.items), 1)
        self.items.append([labe, count])
        self.endInsertRows()

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

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

        g = open("window_temp.txt","w")
        g.write("0")
        g.close()

        MyModel.items.clear()

        self.project = project
        self.model2 = model
        self.similar_word_subwindow()

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

        radio_v_box=QVBoxLayout()
        #v_box= QVBoxLayout()

        button=QPushButton("頻出語の参照")
        button.clicked.connect(lambda: self.showD(self.w, self.project))

        word_v_box=QVBoxLayout()

        wordA_h_box=QHBoxLayout()
        woAlabel=QLabel("検索語")
        self.wordA=QLineEdit()
        wordA_h_box.addWidget(woAlabel)
        wordA_h_box.addWidget(self.wordA)
        wordA_h_box.addStretch(1)

        cal_h_box=QHBoxLayout()
        self.cal_button=QPushButton("検索")
        cal_h_box.addStretch(1)
        cal_h_box.addWidget(self.cal_button)
        self.cal_button.clicked.connect(self.calcuration)

        word_v_box.addLayout(wordA_h_box)
        word_v_box.addLayout(cal_h_box)
        word_v_box.addStretch(1)

        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)

        count_h_box = QHBoxLayout()
        text_label = QLabel("出現回数")
        self.min = QLineEdit()
        self.min.setToolTip("参照する単語の最低出現回数を設定してください")
        self.min.setText("3")
        count_label = QLabel("回以上")
        count_h_box.addWidget(text_label)
        count_h_box.addStretch(2)
        count_h_box.addWidget(self.min)
        count_h_box.addWidget(count_label)

        radio_v_box.addWidget(button)
        radio_v_box.addLayout(radio_h_box)
        radio_v_box.addLayout(count_h_box)
        radio_v_box.addStretch(1)

        radio_box=QHBoxLayout()
        radio_box.addLayout(word_v_box)
        #radio_box.addStretch(1)
        radio_box.addLayout(radio_v_box)

        self.model=MyModel(self)
        self.view=View()
        self.view.setModel(self.model)
        self.view.setUniformRowHeights(True)
        self.view.setColumnWidth(0, 200)


        main_v_layout=QVBoxLayout()

        close_hbox=QHBoxLayout()
        close_button = QPushButton("閉じる", self)
        close_button.clicked.connect(self.exit)
        close_hbox.addStretch(3)
        close_hbox.addWidget(close_button)

        main_v_layout.addLayout(radio_box)
        main_v_layout.addWidget(self.view)
        main_v_layout.addLayout(close_hbox)


        self.w.setGeometry(300, 300, 500, 450)
        self.w.setWindowTitle("類似度の計算")

        self.w.setLayout(main_v_layout)


    def calcuration(self):
        wordA=self.wordA.text()
        self.model.deleRow()
        if wordA == "":
            self.model.deleRow()
            message=QMessageBox.information(self,"お知らせ", "検索語を入力してください", QMessageBox.Ok)
            #print("検索語を入力してください")
        else:
            result=Similar_word_Calcuration(self.project, wordA, self.model2).result #from similar_word_calcuration

            if result == "nothing":
                message=QMessageBox.information(self,"お知らせ", "登録されていない単語です", QMessageBox.Ok)
            elif ((result[0])[1]) ==0.0:
                self.model.deleRow()
                message=QMessageBox.information(self,"お知らせ", "検索に失敗しました<br>ラベルが使用されたプロジェクトでは登録された単語しか検索できません", QMessageBox.Ok)
                #print("検索に失敗しました")
            else:
                for n in result:
                    if n[0] == "</s>":
                        pass
                    else:
                        label=n[0]
                        count=n[1]
                        self.model.addRow(label,count)

    def showD(self, w, project):

        cfg=configparser.ConfigParser()
        file_path = project + ".ini"
        cfg.read(file_path)
        original_data_type=cfg['project']["original_data_type"]

        if int(original_data_type) == 1:
            message=QMessageBox.information(self,"お知らせ", "このプロジェクトでは使用できません", QMessageBox.Ok)
            #print("このプロジェクトでは使用できません")
        else:
            g = open("window_temp.txt","r")
            p=g.readline()
            g.close()

            if p == "0":
                content_word_check = 0
                if self.content_word.isChecked() == True:
                    content_word_check=0
                else:
                    content_word_check=1

                Word_Count(w, project, content_word_check, self.min.text())

            elif p == "1":
                message=QMessageBox.information(self,"お知らせ", "すでにウィンドウが開かれています", QMessageBox.Ok)
                #print("すでにウィンドウが開かれています")
            else:
                message=QMessageBox.information(self,"お知らせ", "error", QMessageBox.Ok)
                #print("error")

    def closeEvent(self, event):
        os.remove("./window_temp.txt")
        time.sleep(0.1)
        self.w.close()

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

    def exit(self):
        os.remove("./window_temp.txt")
        time.sleep(0.1)
        self.w.close()

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