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 character_analysis import near_similar

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

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

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

    def similarity_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("単語1")
        self.wordA=QLineEdit()
        wordA_h_box.addWidget(woAlabel)
        wordA_h_box.addWidget(self.wordA)
        wordA_h_box.addStretch(1)

        peke_h_box=QHBoxLayout()
        peke=QLabel("×")
        peke_h_box.addStretch(1)
        peke_h_box.addWidget(peke)
        peke_h_box.addStretch(1)

        wordB_h_box=QHBoxLayout()
        woBlabel=QLabel("単語2")
        self.wordB=QLineEdit()
        wordB_h_box.addWidget(woBlabel)
        wordB_h_box.addWidget(self.wordB)
        wordB_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(peke_h_box)
        word_v_box.addLayout(wordB_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("5")
        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)

        result_h_box=QHBoxLayout()
        self.res_label=QLabel()
        self.result_label=QLabel()
        result_h_box.addWidget(self.res_label)
        result_h_box.addWidget(self.result_label)

        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_h_box=QHBoxLayout()
        close_button = QPushButton("閉じる", self)
        close_button.clicked.connect(self.exit)
        close_h_box.addStretch(1)
        close_h_box.addWidget(close_button)

        description=QLabel("単語1を単語2に近づける組み合わせを計算します")

        main_v_layout.addWidget(description)
        main_v_layout.addLayout(radio_box)
        main_v_layout.addLayout(result_h_box)
        main_v_layout.addWidget(self.view)
        main_v_layout.addLayout(close_h_box)


        self.w.setGeometry(300, 300, 500, 500)
        self.w.setWindowTitle("特徴の近似化")

        self.w.setLayout(main_v_layout)

    def calcuration(self):
        wordA=self.wordA.text()
        wordB=self.wordB.text()
        self.model.deleRow()

        if wordA == "" or wordB == "":
            #print("単語を入力してください")
            message=QMessageBox.information(self,"お知らせ", "単語を入力してください", QMessageBox.Ok)
        else:
            result=near_similar(self.project, wordA, wordB, self.model2)    #from character_analysis import near_similar

            if result == "nothing":
                message=QMessageBox.information(self,"お知らせ", "登録されていない単語ではないですか？", QMessageBox.Ok)
            else:
                for n in result:
                    label=n[1]
                    count=str(n[0])
                    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:
            #print("このプロジェクトでは使用できません")
            message=QMessageBox.information(self,"お知らせ", "このプロジェクトでは使用できません", QMessageBox.Ok)
        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":
                #print("すでにウィンドウが開かれています")
                message=QMessageBox.information(self,"お知らせ", "すでにウィンドウが開かれています", QMessageBox.Ok)
            else:
                #print("error")
                message=QMessageBox.information(self,"お知らせ", "error", QMessageBox.Ok)


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

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

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

if __name__ == "__main__":
    app=QApplication(sys.argv)
    project = "theme_park"
    #Similarity_SubWindow(project)
    Close_to_SubWindow(project).show()
    #Similarity_SubWindow(project).w.show()
    sys.exit(app.exec_())
