import time, sys, configparser, os, csv, platform
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)



class MyModel(QAbstractItemModel):
    headers = 'ハイパーパラメーター', '設定'
    items = []

    def __init__(self, parent=None):
        super().__init__()
        self.remove_all()

    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, parameter):
        self.beginInsertRows(QModelIndex(), len(self.items), 1)
        #self.items.insert(0,(labe, prediction, text))
        self.items.append((parameter))
        self.endInsertRows()

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

    def all_print(self):
        return self.items

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

        self.bin_model = model


        self.hyper_parameter_window()
        self.parameter(self.bin_model)

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

        window_label = QLabel("学習済みモデルのハイパーパラメーター")

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

        make_csv_button = QPushButton("CSV作成")
        make_csv_button.clicked.connect(self.make_csv)

        close_button = QPushButton("閉じる")
        close_button.clicked.connect(self.w.close)

        buttons = QHBoxLayout()
        buttons.addStretch(1)
        buttons.addWidget(make_csv_button)
        buttons.addWidget(close_button)

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.view)
        main_layout.addLayout(buttons)

        self.w.setGeometry(400, 300, 400, 400)
        self.w.setWindowTitle('ハイパーパラメーターの確認')

        self.w.setLayout(main_layout)


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

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

        print("csvの作成")

    def parameter(self, model):
        self.hyper_parameter_list = []
        title = ("ハイパーパラメーター", "設定")
        self.hyper_parameter_list.append(title)
        model_ = ("学習方法", model.args["model"])
        dim_ = ("次元数", model.args["dim"])
        epoch_ = ("学習回数", model.args["epoch"])
        minCount_ = ("単語の最小出現回数", model.args["minCount"])
        lr_ = ("学習率", model.args["lr"])
        wordNgrams_ = ("単語N-gram", model.args["wordNgrams"])
        if model.args["minn"] == 0 and model.args["maxn"] == 0:
            chara_n_ = ("文字N-gram", "設定なし")
        else:
            chara_n_ = ("文字N-gram", str(model.args["minn"]) + "~" + str(model.args["maxn"]))


        para_list = [model_, dim_, epoch_, minCount_, lr_, wordNgrams_, chara_n_]
        for n in para_list:
            self.model.addRow(n)
            self.hyper_parameter_list.append(n)


    """
        for key in model.args:
            use_hyper_parameter = ["model", "dim", "epoch", "neg", "loss", "lr", "maxn", "minn", "minCount", "wordNgrams", "ws"]
            for hyper_parameter in use_hyper_parameter:
                if key == hyper_parameter:
                    key_value = (key, model.args[key])
                    self.model.addRow(key_value)
                    self.hyper_parameter_list.append(key_value)
    """

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

if __name__=="__main__":
    model_ = FastText('./fastText/cross_category.bin')
    parameter(model)
