import sys, os, csv, configparser, codecs, platform
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
import matplotlib.font_manager as fm
import pandas as pd
from pyfasttext import FastText #windows版ではコメントアウト
from operator import itemgetter
from statistics import variance
#import gensim
from PIL import Image  #使う
from matplotlib.font_manager import FontProperties
from scipy.stats import pearsonr

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)

import matplotlib as mpl
from matplotlib.font_manager import FontProperties

from main_config import main_Config
from word_count_window import count


class MyModel(QAbstractItemModel):

    #headers = "","",""#head_word
    #items = []

    def __init__(self, project, word_a, word_b):#, parent=None):
        super().__init__()


        a=["","相関","p値","分散"]
        head_word=word_a
        a.extend(head_word)
        self.headers= a
        self.items = []

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

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

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 Correlation_SubWindow(QWidget):
    def __init__(self, project, bin_model, wordA, wordB, input_data):
        super().__init__()

#        config=configparser.ConfigParser()
#        config.read('main.ini')
#        self.using_os=config['settings']["os"]
        self.mysql_id, self.mysql_pass, self.projects, self.root_path, self.using_os = main_Config()

        self.project = project
        self.bin_model = bin_model
        self.wordA = wordA
        self.wordB = wordB
        self.input_data = input_data

        self.correlation_result_window()

        ex_data = ["入力データ", "", "", ""] + input_data
        self.model.addRow(ex_data)

        self.get_similarity()

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

        self.model=MyModel(self.project, self.wordA, self.wordB)
        self.view=View()
        self.view.setModel(self.model)
        self.view.setUniformRowHeights(True)
        self.view.setColumnWidth(0, 150)

        csv_h_box=QHBoxLayout()
        plot_button=QPushButton("プロット")
        csv_push_button=QPushButton("csvで出力")
        close_button=QPushButton("閉じる")
        csv_h_box.addStretch(2)
        if os.name == "nt":
            pass
        else:
            csv_h_box.addWidget(plot_button)
        csv_h_box.addWidget(csv_push_button)
        csv_h_box.addWidget(close_button)
        plot_button.clicked.connect(self.plot)
        close_button.clicked.connect(self.w.close)
        csv_push_button.clicked.connect(self.make_csv)

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

        self.w.setGeometry(600, 200, 800, 650)
        self.w.setWindowTitle('外部データとの相関')

        self.w.setLayout(main_layout)

    def plot(self):
        try:
            fp = self.font()

            for index in self.view.selectedIndexes():
                #print(index.row())
                if index.column() == 0:
                    n = index.row()
                    self.x_axis_label=(self.model.items[n])[0]
                    self.x_label=self.model.items[n]    #matplotでのラベルに使用
                    self.x_label=list(self.x_label)

                    #print(self.x_label)

                    del self.x_label[0:4]
                    #del self.x_label[0]
                    #del self.x_label[0]

                    self.x_label=tuple(self.x_label)    #X軸の値
                    print(self.x_label)

            #print("a",self.x_label)

            self.y_label=tuple(self.input_data) #y軸の値

            x=np.array(self.x_label)
            y=np.array(self.y_label)
            indexA=self.wordA
            df = pd.DataFrame({'x':x, 'y':y}, index=indexA)
            fig, ax = plt.subplots()
            df.plot('x', 'y', kind='scatter', ax=ax)

            plt.xlabel("", fontproperties=fp)
            plt.ylabel("", fontproperties=fp)
            plt.title(self.x_axis_label + "との相関", fontproperties=fp)

            for k, v in df.iterrows():
                ax.annotate(k, v, fontproperties=fp)

            plt.grid()
            plt.savefig(self.x_axis_label + ".png")
            img = Image.open(self.x_axis_label + ".png")
            img.show()

        except Exception as e:
            print(e)
            message=QMessageBox.information(self,"お知らせ", "プロットする単語を選んでください", QMessageBox.Ok)

    def font(self):
        if os.name == "posix":
            system_os = platform.system()
            if system_os == "Darwin":
                fp = FontProperties(fname=r'/System/Library/Fonts/ヒラギノ明朝 ProN.ttc')
            else:
                fp = FontProperties(fname=r'/usr/share/fonts/truetype/takao-gothic/TakaoPGothic.ttf')
            return fp
        else:
            pass

    def make_csv(self):
        header = tuple(self.model.headers)
        content = self.model.items
        #print(header)
        #print(content)
        alls=[]
        alls.append(header)
        alls.extend(content)
        #print(alls)

        if len(content) == 0:
            message=QMessageBox.information(self,"お知らせ", "保存するデータがありません", QMessageBox.Ok)
            #print("保存するデータがありません")
        else:
            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(alls)
                    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(alls)
                    f.close()
                else:
                    f = open(save_file_path, "w", encoding='utf-8')
                    write = csv.writer(f, lineterminator='\n')
                    write.writerows(alls)
                    f.close()
            except Exception as e:
                print(e)


    def get_similarity(self):
        all_similarity = []
        for m in self.wordB:
            word_similarity = []
            for n in self.wordA:
                a = self.bin_model.similarity(m, n)
                word_similarity.append(a)

            result = self.correlation_calcuration(word_similarity, m)

            result += word_similarity

            all_similarity.append(result)

        all_similarity.sort(key = itemgetter(2), reverse = False)

        for l in all_similarity:
            self.model.addRow(l)

    def correlation_calcuration(self, word_similarity, word):
        correlation, possibility = pearsonr(self.input_data, word_similarity)   #scipyでの相関計算
        similarity_variance = variance(word_similarity)
        result = [word, str(correlation), str(possibility), str(similarity_variance)]    #scipyでの相関計算
        return result



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

if __name__=="__main__":
    app=QApplication(sys.argv)
    project="aqua"
    path="./fastText/" + project + ".bin"
    model = FastText(path)
    wordA = ["海遊館", "沖縄美ら海水族館", "鴨川シーワールド", "鳥羽水族館", "名古屋港水族館"]
    wordB = ["夕方", "ジュゴン", "アシカ"]
    input_data = [float(217), float(281), float(80), float(83), float(199)]
    Correlation_SubWindow(project, model, wordA, wordB, input_data).show()
    sys.exit(app.exec_())

    #Correlation_SubWindow(project, model, wordA, wordB, input_data).get_similarity()
