import sys, configparser, os, time, MySQLdb
from multiprocessing import Process

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 mysql_fasttext import Mysql_Fasttext
from long_time import Warning_Window
from mysql_learn_sampling import train_test_data_reset
from main_config import main_Config
from write_project_ini import write_pro_ini


class distirbuted_SubWindow(QWidget):

    def __init__(self, project):
        super().__init__()
        self.project = project
        self.distributed_window()
        self.mysql_id, self.mysql_pass, self.no_use_projects, self.root_path, self.using_os = main_Config()

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

        cfg_type=configparser.ConfigParser()
        file_path = self.project + ".ini"
        cfg_type.read(file_path)
        nums_of_label = cfg_type['project']["nums_of_label"]

        label=QLabel("fasttextの設定")

        min_count_h_box=QHBoxLayout()
        min_label=QLabel("最小出現回数")
        min_label.setToolTip("出現回数が何回以上の単語を分析に使用しますか?")
        self.min=QLineEdit()
#        if nums_of_label == "0":
#            para_min = "5"
#        else:
#            para_min = "1"
        self.min.setText("5")
        self.min.setToolTip("出現回数が何回以上の単語を分析に使用しますか?")
        min_count_h_box.addWidget(min_label)
        min_count_h_box.addStretch(1)
        min_count_h_box.addWidget(self.min)

        dim_h_box=QHBoxLayout()
        dim_label=QLabel("分散表現の次元数")
        dim_label.setToolTip("分散表現を何次元にしますか?")
        self.dim=QLineEdit()
        self.dim.setText("100")
        self.dim.setToolTip("分散表現を何次元にしますか?")
        dim_h_box.addWidget(dim_label)
        dim_h_box.addStretch(2)
        dim_h_box.addWidget(self.dim)

        labelB=QLabel("最大は300です")
        labelB.setAlignment(Qt.AlignRight)

        epoch_h_box=QHBoxLayout()
        epoch_label=QLabel("学習回数（epoch）")
        epoch_label.setToolTip("学習回数を設定します")
        self.epoch=QLineEdit()
        self.epoch.setText("5")
        self.epoch.setToolTip("5から50が推奨されています")
        epoch_h_box.addWidget(epoch_label)
        epoch_h_box.addStretch(2)
        epoch_h_box.addWidget(self.epoch)

        lr_h_box=QHBoxLayout()
        lr_label=QLabel("学習率（learning rate）")
        lr_label.setToolTip("学習率を設定します")
        self.lr=QLineEdit()
#        if nums_of_label == "0":
#            para_lr = "0.05"
#        else:
#            para_lr = "0.1"
        self.lr.setText("0.05")
        self.lr.setToolTip("0.01から1.0が推奨されています")
        lr_h_box.addWidget(lr_label)
        lr_h_box.addStretch(2)
        lr_h_box.addWidget(self.lr)

        word_ngram_h_box=QHBoxLayout()
        word_ngram_label=QLabel("単語Ngram")
        word_ngram_label.setToolTip("単語Ngramを設定します")
        self.word_ngram=QLineEdit()
        self.word_ngram.setText("1")
        self.word_ngram.setToolTip("1から5が推奨されています")
        word_ngram_h_box.addWidget(word_ngram_label)
        word_ngram_h_box.addStretch(2)
        word_ngram_h_box.addWidget(self.word_ngram)

        ch_ngram_h_box=QHBoxLayout()
        ch_ngram_label=QLabel("文字Ngram")
        ch_ngram_label.setToolTip("文字Ngramを設定します")
        self.min_ngram=QLineEdit()
#        if nums_of_label == "0":
#            para_min_ngram = "3"
#        else:
#            para_min_ngram = "0"
        self.min_ngram.setText("3")
        self.min_ngram.setToolTip("sabwordsを使用しない場合は0にしてください")
        self.max_ngram=QLineEdit()
#        if nums_of_label == "0":
#            para_max_ngram = "6"
#        else:
#            para_max_ngram = "0"
        self.max_ngram.setText("6")
        self.max_ngram.setToolTip("sabwordsを使用しない場合は0にしてください")
        mark=QLabel("~")
        ch_ngram_h_box.addWidget(ch_ngram_label)
        ch_ngram_h_box.addStretch(1)
        ch_ngram_h_box.addWidget(self.min_ngram)
        ch_ngram_h_box.addWidget(mark)
        ch_ngram_h_box.addWidget(self.max_ngram)

        self.process_label=QLabel()

        button_h_box=QHBoxLayout()
        process_button=QPushButton("実行")
        process_button.clicked.connect(self.process)
        cancelB=QPushButton("キャンセル")
        cancelB.clicked.connect(self.w.close)
        button_h_box.addStretch(2)
        button_h_box.addWidget(process_button)
        button_h_box.addWidget(cancelB)

        main_v_layout=QVBoxLayout()
        main_v_layout.addLayout(min_count_h_box)
        main_v_layout.addLayout(dim_h_box)
        main_v_layout.addWidget(labelB)
        main_v_layout.addLayout(epoch_h_box)
        main_v_layout.addLayout(lr_h_box)
        main_v_layout.addLayout(word_ngram_h_box)
#        if nums_of_label != "0":
#            pass
#        else:
#            main_v_layout.addLayout(ch_ngram_h_box)
        main_v_layout.addLayout(ch_ngram_h_box)
        main_v_layout.addStretch(1)
        main_v_layout.addWidget(self.process_label)
        main_v_layout.addLayout(button_h_box)


        self.w.setGeometry(300, 300, 350, 150)
        self.w.setWindowTitle('分散表現の取得(skip-gram)')
        self.w.setLayout(main_v_layout)



    def process(self):
        self.initialize()

        mincount = self.min.text()
        dim = self.dim.text()
        epoch = self.epoch.text()
        lr = self.lr.text()
        word_ngram = self.word_ngram.text()
        minn = self.min_ngram.text()
        maxn = self.max_ngram.text()

        if dim.isdigit() and mincount.isdigit():
            if int(dim) >300:
                message=QMessageBox.information(self, "お知らせ","300以下で設定してください", QMessageBox.Ok)
                #print("300以下で設定してください")
            else:
                warn_sub = Warning_Window(self.project, mincount, dim, epoch, lr, word_ngram, minn, maxn, "0")  #最後の引数０はskip-gramで処理することを意味している
                warn_sub.show()

                #Mysql_Fasttext(self.project, mincount, dim) # from mysql_fasttext

                time.sleep(0.2)

                self.count_using_text()

                time.sleep(0.1)

                self.w.close()

#############################################################################

        else:
            message=QMessageBox.information(self, "お知らせ","数字を入力してください", QMessageBox.Ok)
            #print("数字を入力してください")

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

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

            #sql="select count(*) from text_table"
            #cursor.execute(sql)
            #all_nums=((cursor.fetchall())[0])[0]

            #time.sleep(0.1)

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

            if sampling == "1":
                sql="select count(*) from text_table where sampling = 1"
            else:
                sql="select count(*) from text_table"

            cursor.execute(sql)
            sam_nums=((cursor.fetchall())[0])[0]

            using_text = str(sam_nums)

            write_pro_ini(self.project).main(discrimination="0", count_texts_analysis=using_text, dimensions=self.dim.text())   #iniファイルを修正
        except Exception as e:
            print(e)

    def initialize(self):
        cfg=configparser.ConfigParser()
        file_path = self.project + ".ini"
        cfg.read(file_path)
        sampleA=cfg['project']["sample"]

        if int(sampleA) >=10:
            sampleA = str(int(sampleA) - 10)
            write_pro_ini(self.project).main(sample=sampleA, train_test="")   #iniファイルを修正

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

        else:
            pass


if __name__=="__main__":
    app=QApplication(sys.argv)

    project="test"

    ex= distirbuted_SubWindow(project)
    distirbuted_SubWindow(project).count_using_text()
    #distirbuted_SubWindow(project).show()
    sys.exit(app.exec_())
