import time, sys, os, configparser
from pyfasttext import FastText

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 word_count_window import count
from pict_word_correlation import Correlation_internal_SubWindow

class ListView(QListWidget):
    def __init__(self, *args, **kwargs):
        super(ListView, self).__init__(*args, **kwargs)

    def removeSelectedItem(self):
        model    = self.model()
        selModel = self.selectionModel()

        while True:
            indexes = selModel.selectedIndexes()
            if not indexes:
                break

            model.removeRow(indexes[0].row())

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Delete:
            self.removeSelectedItem()
            return

        super(ListView, self).keyPressEvent(event)

class Correlation_internal_select_word_SubWindow(QWidget):

    def __init__(self, project, model):
        super().__init__()
        self.project=project
        self.model = model
        self.selected_word = ""
        self.selected_word_a = ""
        self.selected_word_b = ""

        if os.name =="nt":
            self.worda_limitation=5
        elif os.name=="posix":
            self.worda_limitation=20

        if os.name =="nt":
            self.wordb_limitation=20
        elif os.name=="posix":
            self.wordb_limitation=200

        self.cognitive_map_window()

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


        candidate_box=QHBoxLayout()

        radio_v_box = QVBoxLayout()
        radio_vv_box=QVBoxLayout()
        search_label=QLabel("使用可能な単語の検索")
        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_vv_box.addWidget(self.content_word)
        radio_vv_box.addWidget(self.all_word)

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

        search_button=QPushButton("検索")
        search_button.clicked.connect(self.search_word)

        radio_v_box.addStretch(3)
        radio_v_box.addWidget(search_label)
        radio_v_box.addStretch(1)
        radio_v_box.addLayout(radio_vv_box)
        radio_v_box.addStretch(1)
        radio_v_box.addLayout(count_v_box)
        radio_v_box.addStretch(1)
        radio_v_box.addWidget(search_button)
        radio_v_box.addStretch(3)

        word_a_box=QVBoxLayout()
        word_a_label=QLabel("プロットする単語(最大" + str(self.worda_limitation) + "語です)")
        add_a_box=QHBoxLayout()
        self.add_word_a=QLineEdit()
        self.add_word_a.setToolTip("複数の単語を追加する場合は「スペース」で区切ってください")
        add_word_a_button=QPushButton("追加")
        add_word_a_button.clicked.connect(self.input_word_a)
        add_a_box.addWidget(self.add_word_a)
        add_a_box.addWidget(add_word_a_button)
        self.word_a_items=ListView()  #word_aはプロットする単語
        self.word_a_items.setSelectionMode(QAbstractItemView.ExtendedSelection)
        a_limit_box=QHBoxLayout()
        self.word_a_limit=QLabel("/" + str(self.worda_limitation))
        a_limit_box.addStretch(1)
        a_limit_box.addWidget(self.word_a_limit)
        word_a_box.addWidget(word_a_label)
        word_a_box.addLayout(add_a_box)
        word_a_box.addWidget(self.word_a_items)
        word_a_box.addLayout(a_limit_box)
        self.word_a_items.itemSelectionChanged.connect(self.change_item_a)

        to_from_a_box=QVBoxLayout()
        to_word_a_button=QPushButton(">")
        to_word_a_button.clicked.connect(self.to_word_a)
        from_word_a_button=QPushButton("<")
        from_word_a_button.clicked.connect(self.from_word_a)
        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)

        candidate_v_box=QVBoxLayout()
        candidate_label=QLabel("候補の単語")
        self.candidate_word=QListWidget()    #candidate_wordは候補の単語
        self.candidate_word.setSelectionMode(QAbstractItemView.ExtendedSelection)   #複数選択を可能にする
        candidate_v_box.addWidget(candidate_label)
        candidate_v_box.addWidget(self.candidate_word)
        self.candidate_word.itemSelectionChanged.connect(self.change_item)

        to_from_b_box=QVBoxLayout()
        to_word_b_button=QPushButton(">")
        to_word_b_button.clicked.connect(self.to_word_b)
        from_word_b_button=QPushButton("<")
        from_word_b_button.clicked.connect(self.from_word_b)
        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_box=QVBoxLayout()
        word_b_label=QLabel("軸として使用する単語(最大" + str(self.wordb_limitation) + "語です)")
        add_b_box=QHBoxLayout()
        self.add_word_b=QLineEdit()
        add_word_b_button=QPushButton("追加")
        self.add_word_b.setToolTip("複数の単語を追加する場合は「スペース」で区切ってください")
        add_word_b_button.clicked.connect(self.input_word_b)
        add_b_box.addWidget(self.add_word_b)
        add_b_box.addWidget(add_word_b_button)
        self.word_b_items=ListView()  #word_bは軸に使用する単語
        self.word_b_items.setSelectionMode(QAbstractItemView.ExtendedSelection)
        b_limit_box=QHBoxLayout()
        self.word_b_limit=QLabel("/" + str(self.wordb_limitation))
        b_limit_box.addStretch(1)
        b_limit_box.addWidget(self.word_b_limit)
        word_b_box.addWidget(word_b_label)
        word_b_box.addLayout(add_b_box)
        word_b_box.addWidget(self.word_b_items)
        word_b_box.addLayout(b_limit_box)
        self.word_b_items.itemSelectionChanged.connect(self.change_item_b)

        push_button_v_box=QVBoxLayout()
        push_button_v_box.addLayout(to_from_a_box)
        push_button_v_box.addLayout(to_from_b_box)

        for_analyze_v_box=QVBoxLayout()
        for_analyze_v_box.addLayout(word_a_box)
        for_analyze_v_box.addStretch(1)
        for_analyze_v_box.addLayout(word_b_box)

        button_h_box=QHBoxLayout()
        process_button=QPushButton("実行")
        process_button.clicked.connect(self.process)
        cancelB=QPushButton("閉じる")
        cancelB.clicked.connect(self.close_window)
        button_h_box.addStretch(2)
        button_h_box.addWidget(process_button)
        button_h_box.addWidget(cancelB)

        candidate_box.addLayout(radio_v_box)
        candidate_box.addStretch(1)
        candidate_box.addLayout(candidate_v_box)
        candidate_box.addLayout(push_button_v_box)
        candidate_box.addLayout(for_analyze_v_box)

        self.w.setGeometry(500, 200, 800, 650)
        self.w.setWindowTitle('単語間の相関の計算')

        main_layout = QVBoxLayout()
        main_layout.addLayout(candidate_box)
        main_layout.addStretch(1)
        main_layout.addLayout(button_h_box)
        self.w.setLayout(main_layout)

    def process(self):

        if len(self.word_a_items) == 0 or len(self.word_b_items) == 0:
            message=QMessageBox.information(self, "お知らせ","単語を追加してください", QMessageBox.Ok)
            #print("単語を追加してください")
        elif len(self.word_a_items) > self.worda_limitation:
            message=QMessageBox.information(self, "お知らせ","プロットできる単語は" + str(self.worda_limitation) + "以下です", QMessageBox.Ok)
            #print("プロットできる単語は20以下です")
        elif len(self.word_b_items) > self.wordb_limitation:
            message=QMessageBox.information(self, "お知らせ","軸の候補にできるきる単語は" + str(self.wordb_limitation) + "以下です", QMessageBox.Ok)
            #print("軸の候補にできるきる単語は200以下です")
        else:

            wordA=[]
            for i in range(self.word_a_items.count()):
                wordA.append(self.word_a_items.item(i).text())

            wordB=[]
            for i in range(self.word_b_items.count()):
                wordB.append(self.word_b_items.item(i).text())

            subwindow=Correlation_internal_SubWindow(self.project, self.model, wordA, wordB) #from alfa_pict_word_correlation import Correlation_internal_SubWindow
            subwindow.show()

        pass


    def input_word_a(self):
        if self.add_word_a.text() =="":
            pass
        else:
            add_word_a = self.add_word_a.text().replace("　", " ")
            add_word_a = add_word_a .split(" ")
            for n in add_word_a:
                self.word_a_items.addItem(n)
            self.add_word_a.clear()
        count_word_a= len(self.word_a_items)
        self.word_a_limit.setText(str(count_word_a) + "/" + str(self.worda_limitation))


    def input_word_b(self):
        if self.add_word_b.text() =="":
            pass
        else:
            add_word_b = self.add_word_b.text().replace("　", " ")
            add_word_b = add_word_b .split(" ")
            for n in add_word_b:
                self.word_b_items.addItem(n)
            self.add_word_b.clear()
        count_word_b= len(self.word_b_items)
        self.word_b_limit.setText(str(count_word_b) + "/" + str(self.wordb_limitation))

    def to_word_a(self):
        if self.selected_word == "":
            pass
        else:
            for n in self.selected_word:
                self.word_a_items.addItem(n)
            for SelectedItem in self.candidate_word.selectedItems():
                self.candidate_word.takeItem(self.candidate_word.row(SelectedItem))
        count_word_a= len(self.word_a_items)
        self.word_a_limit.setText(str(count_word_a) + "/" + str(self.worda_limitation))

    def to_word_b(self):
        if self.selected_word == "":
            pass
        else:
            for n in self.selected_word:
                self.word_b_items.addItem(n)
            for SelectedItem in self.candidate_word.selectedItems():
                self.candidate_word.takeItem(self.candidate_word.row(SelectedItem))
        count_word_b= len(self.word_b_items)
        self.word_b_limit.setText(str(count_word_b) + "/" + str(self.wordb_limitation))

    def change_item(self):
        a=self.candidate_word.selectedItems()
        self.selected_word=[]
        for n in a:
            self.selected_word.append(n.text())

    def from_word_a(self):
        if self.selected_word_a == "":
            pass
        else:
            for n in self.selected_word_a:
                self.candidate_word.addItem(n)
            for SelectedItem in self.word_a_items.selectedItems():
                self.word_a_items.takeItem(self.word_a_items.row(SelectedItem))
        count_word_a= len(self.word_a_items)
        self.word_a_limit.setText(str(count_word_a) + "/" + str(self.worda_limitation))

    def from_word_b(self):
        if self.selected_word_b == "":
            pass
        else:
            for n in self.selected_word_b:
                self.candidate_word.addItem(n)
            for SelectedItem in self.word_b_items.selectedItems():
                self.word_b_items.takeItem(self.word_b_items.row(SelectedItem))
        count_word_b= len(self.word_b_items)
        self.word_b_limit.setText(str(count_word_b) + str(self.wordb_limitation))

    def change_item_a(self):
        a=self.word_a_items.selectedItems()
        self.selected_word_a=[]
        for n in a:
            self.selected_word_a.append(n.text())

    def change_item_b(self):
        a=self.word_b_items.selectedItems()
        self.selected_word_b=[]
        for n in a:
            self.selected_word_b.append(n.text())

    def search_word(self):
        cfg=configparser.ConfigParser()
        file_path = self.project + ".ini"
        cfg.read(file_path)
        data_type=cfg['project']["original_data_type"]

        if data_type == "1":
            message=QMessageBox.information(self, "お知らせ","この機能はご使用できません", QMessageBox.Ok)
        else:
            if self.content_word.isChecked() == True:
                content_word_check=0
            else:
                content_word_check=1
            minn=self.min.text()
            res = count(self.project, content_word_check, minn).word_list
            self.insert_candidate_word(res)

    def insert_candidate_word(self, words):
        for n in words:
            n=n[0]
            self.candidate_word.addItem(n)

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

    #def closeEvent(self, event):
    #    self.model.items.clear()

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

if __name__=="__main__":
    app=QApplication(sys.argv)
    project="aqua"
    path="./fastText/" + project + ".bin"
    model = FastText(path)
    Correlation_select_word_SubWindow(project, model).show()
    sys.exit(app.exec_())
