import sys, configparser, os, time, subprocess, codecs, csv, platform, MySQLdb

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 main_config import main_Config

class Export_morpheme_SubWindow(QWidget):
    def __init__(self, project):
        super().__init__()

        self.project=project

        self.export_morpheme_window()

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

        main_label=QLabel("エクスポートするデータの選択")

        radio_v_box = QVBoxLayout()
        self.all_sentenece = QRadioButton("全文章") #基本形を使用
        self.used_sentence = QRadioButton("分析に使用した文章")  #表層形を使用
        self.used_sentence.toggle()
        self.button_group = QButtonGroup()
        self.button_group.addButton(self.used_sentence)
        self.button_group.addButton(self.all_sentenece)
        radio_v_box.addWidget(self.used_sentence)
        radio_v_box.addWidget(self.all_sentenece)

        check_v_box=QVBoxLayout()
        self.text_checkbox = QCheckBox("登録されたテキスト", self)
        self.morpheme_checkbox = QCheckBox("形態素解析済みテキスト", self)
        self.sentence_vector_checkbox = QCheckBox("テキストの分散表現", self)
        self.re_labeled_checkbox = QCheckBox("カテゴリー横断分析の再ラベリングの結果", self)
        check_v_box.addWidget(self.text_checkbox)
        check_v_box.addWidget(self.morpheme_checkbox)
        check_v_box.addWidget(self.sentence_vector_checkbox)
        check_v_box.addWidget(self.re_labeled_checkbox)

        button_h_box=QHBoxLayout()
        export_csv_button=QPushButton("csv出力")
        export_csv_button.clicked.connect(self.export_csv)
        close_button=QPushButton("閉じる")
        close_button.clicked.connect(self.close_window)
        button_h_box.addStretch(1)
        button_h_box.addWidget(export_csv_button)
        button_h_box.addWidget(close_button)

        main_layout=QVBoxLayout()
        main_layout.addWidget(main_label)
        main_layout.addLayout(radio_v_box)
        main_layout.addLayout(check_v_box)
        main_layout.addLayout(button_h_box)

        self.w.setGeometry(700, 300, 400, 200)
        self.w.setWindowTitle('データのエクスポート')

        self.w.setLayout(main_layout)

    def export_csv(self):

        ###########################################################
        #出力する文章を選択
        used_check = 0
        if self.used_sentence.isChecked() == True:
            used_check=0
        else:
            used_check=1

        ###########################################################
        #登録されたテキストを出力
        all_text = ""
        #print(self.text_checkbox.checkState())
        if self.text_checkbox.checkState() > 0:
            all_text="original_sentence"
        else:
            all_text=""

        ###########################################################
        #登録されたテキストを出力
        morpheme_text = ""
        #print(self.text_checkbox.checkState())
        if self.morpheme_checkbox.checkState() > 0:
            morpheme_text="morpheme"
        else:
            morpheme_text=""

        ##########################################################
        #テキストの分散表現
        vector_text = ""
        #print(self.text_checkbox.checkState())
        if self.sentence_vector_checkbox.checkState() > 0:
            vector_text="sentence_vector"
        else:
            vector_text=""

        ##########################################################
        #カテゴリー横断分析の再ラベリングの結果
        re_labeled = ""
        #print(self.text_checkbox.checkState())
        if self.re_labeled_checkbox.checkState() > 0:
            re_labeled="disc_code "
        else:
            re_labeled=""

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

        if used_check == 0:
            if sampling == 0:
                sample = ""
            elif sampling ==1:
                sample = " where sampling = " + str(sampling)
            elif sampling == 10 or sampling ==11:
                sample = " where train_test_data = 1"
            else:
                print("エラー発生")
        else:
            sample = ""

        selected_column = [all_text, morpheme_text, vector_text, re_labeled]

        selected = []
        for n in selected_column:
            if n == "":
                pass
            else:
                selected.append(n)

        columns = len(selected)

        for_sql = str(selected)
        for_sql = for_sql.replace("]","").replace("[","").replace("'","")

        if columns == 0:
            message=QMessageBox.information(self, "お知らせ","エクスポートするデータを選択してください", QMessageBox.Ok)
        else:
            sql = "select " + for_sql + " from text_table" + sample

            result = self.import_from_mysql(self.project, sql)
            self.export_file(self.project, result)

    def export_file(self, project, result):
        try:
            folder_path = folder_path = os.getcwd()
            ########################################################
            frame=QFileDialog.getSaveFileName(self, "保存フォルダーの選択", folder_path,filter=("csv files(*.csv)"))
            ########################################################
            save_file_path = frame[0]# + ".csv"

            system_os = platform.system()
            if system_os == "Darwin":
                f = open(save_file_path, "w", encoding='utf-16')
                write = csv.writer(f, dialect='excel-tab', lineterminator='\n')
                write.writerows(result)
                f.close()
            elif os.name == "nt":
                f = open(save_file_path, "w", encoding='utf-16')
                write = csv.writer(f, dialect='excel-tab', lineterminator='\n')
                write.writerows(resutl)
                f.close()
            else:
                f = open(save_file_path, "w", encoding='utf-8')
                write = csv.writer(f, lineterminator='\n')
                write.writerows(result)
                f.close()
        except Exception as e:
            print(e)


    def import_from_mysql(self, project, sql):
        mysql_id, mysql_pass, projects, root_path, using_os = main_Config()
        try:
            conn=MySQLdb.connect(db=project, user=mysql_id, passwd=mysql_pass, charset="utf8mb4")
            cursor=conn.cursor()

            time.sleep(0.1)

            cursor.execute(sql)
            all_sentence = cursor.fetchall()

            time.sleep(0.1)

            conn.commit()
            cursor.close()
            conn.close()

            return all_sentence
        except Exception as e:
            print(e)

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

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

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