import sys, configparser, time, os, csv, platform

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 divide_class import divide_Class

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

    def __init__(self, project):
         super(Classify_SubWindow,self).__init__()
         self.project=project

         self.file_path = ""

         self.classify_subwindow()

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

        ref_h_box=QHBoxLayout()
        reference_button=QPushButton("参照")
        reference_button.clicked.connect(self.reference)
        self.ref_file=QLineEdit()
        ref_h_box.addWidget(reference_button)
        ref_h_box.addWidget(self.ref_file)
        ref_h_box.addStretch(2)

        process_h_box=QHBoxLayout()
        process_button=QPushButton("実行")
        process_button.clicked.connect(self.process)
        process_h_box.addWidget(process_button)
        process_h_box.addStretch(1)

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

        close_h_box=QHBoxLayout()
        export_csv=QPushButton("csv出力")
        export_csv.clicked.connect(self.csv_export)
        close_button=QPushButton("閉じる")
        close_button.clicked.connect(self.close_window)
        close_h_box.addStretch(2)
        close_h_box.addWidget(export_csv)
        close_h_box.addWidget(close_button)

        main_v_layout=QVBoxLayout()
        main_v_layout.addLayout(ref_h_box)
        main_v_layout.addLayout(process_h_box)
        #main_v_layout.addStretch(0.2)
        main_v_layout.addWidget(self.view)
        #main_v_layout.addStretch(0.2)
        main_v_layout.addLayout(close_h_box)

        self.w.setGeometry(600, 300, 650, 400)
        self.w.setWindowTitle('テキストの分類')
        self.w.setLayout(main_v_layout)

    def csv_export(self):
        alls = self.model.all_print()

        if len(alls) == 0:
            message=QMessageBox.information(self,"お知らせ", "保存するデータがありません", QMessageBox.Ok)
            #print("保存するデータがありません")
        else:
            try:
                now_path = os.getcwd()
                ########################################################
                frame=QFileDialog.getSaveFileName(self, "保存フォルダーの選択", now_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(alls)
                    f.close()
                else:
                    f = open(save_file_path, "w")
                    write = csv.writer(f, lineterminator='\n')
                    write.writerows(alls)
                    f.close()
            except Exception as e:
                print(e)

    def process(self):
        self.model.remove_all()
        if self.file_path != "":
            result = divide_Class(self.project, self.file_path)
            time.sleep(0.1)

            for n in result:
                label=n[0]
                evaluation=n[1]
                text=n[2]
                self.model.addRow(label, evaluation, text)

        else:
            message=QMessageBox.information(self, "お知らせ","分類するファイルを指定してください", QMessageBox.Ok)
            #print("分類するファイルを指定してください")

    def reference(self):
        now_path = os.getcwd()
        frame=QFileDialog.getOpenFileName(self, "ファイルの選択", now_path, filter=("text files(*.txt)"))

        filepath=frame[0]
        filename=frame[0].split("/")
        filename=filename[-1]
        self.file_path=filepath
        #print(self.file_path)
        self.filename=filename

        self.ref_file.setText(self.filename)

    def close_window(self):
        self.model.remove_all()
        #time.sleep(0.1)
        self.w.close()

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

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