import MySQLdb, time, configparser, platform
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
from numpy import array
import matplotlib as mpl
np.set_printoptions(threshold=np.inf)
font = {"family":"Noto Sans CJK JP"}
mpl.rc('font', **font)
from main_config import main_Config
from matplotlib.font_manager import FontProperties


def draw_elbow_func(project, disc_code):

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

    reset(project,mysql_id,mysql_pass)
    time.sleep(0.1)

    vecs=import_from_sql(project,mysql_id,mysql_pass, disc_code)
    time.sleep(0.1)

    vectors=get_array(vecs, using_os)
    time.sleep(0.1)

    elbow(vectors)#クラスター数の決定

def elbow(vectors):
    system_os = platform.system()
    if system_os == "Darwin":
        fp = FontProperties(fname=r'/System/Library/Fonts/ヒラギノ明朝 ProN.ttc')
        li=[]
        for i,j in vectors:
            li.append(j)

        distortions = []
        for i  in range(1,21):                # 1~10クラスタまで一気に計算
            km = KMeans(n_clusters=i,
                        init='k-means++',     # k-means++法によりクラスタ中心を選択
                        n_init=10,
                        max_iter=300,
                        random_state=0)
            km.fit(li)                         # クラスタリングの計算を実行
            distortions.append(km.inertia_)   # km.fitするとkm.inertia_が得られる

        plt.plot(range(1,21),distortions,marker='o')
        plt.xticks( [0,2,4,6,8,10,12,14,16,18,20] )
        plt.xlabel('Number of clusters')
        plt.ylabel('Distortion')
        plt.title("エルボー図")
        plt.savefig("エルボー図.png")
        img = Image.open("エルボー図.png")

    else:
        font_path = "/usr/share/fonts/truetype/takao-gothic/TakaoPGothic.ttf"
        font_prop = FontProperties(fname=font_path)
        mpl.rcParams['font.family'] = font_prop.get_name()
        #mpl.rcParams['font.family'] = "TakaoExMincho"
        li=[]
        for i,j in vectors:
            li.append(j)

        distortions = []
        for i  in range(1,21):                # 1~10クラスタまで一気に計算
            km = KMeans(n_clusters=i,
                        init='k-means++',     # k-means++法によりクラスタ中心を選択
                        n_init=10,
                        max_iter=300,
                        random_state=0)
            km.fit(li)                         # クラスタリングの計算を実行
            distortions.append(km.inertia_)   # km.fitするとkm.inertia_が得られる

        plt.plot(range(1,21),distortions,marker='o')
        plt.xticks( [0,2,4,6,8,10,12,14,16,18,20] )
        plt.xlabel('Number of clusters')
        plt.ylabel('Distortion')
        plt.title("エルボー図")
        plt.show()


def get_array(vecs, using_os):
    vectors=[]
    for vec in vecs:
        #print(vec)
        sentence_id=vec[0]
        vec=(vec[1])
        vec=vec.split(" ")
        sen_vector=[]
        if using_os == "posix":
            for ve in vec:
                if ve == "":
                    pass
                else:
                    ve=float(ve)
                    ve=round(ve,5)
                    #print(ve)
                    sen_vector.append(ve)
        elif using_os == "nt":
            for ve in vec:
                if ve == "\r":
                    pass
                else:
                    ve=float(ve)
                    ve=round(ve,5)
                    #print(ve)
                    sen_vector.append(ve)
        else:
            pass
        sen_id_vector=(sentence_id,sen_vector)
        vectors.append(sen_id_vector)
    return vectors

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

    sql="select sentence_id, sentence_vector from text_table where disc_code=" + disc_code
    cursor.execute(sql)
    vecs=list(cursor.fetchall())
    time.sleep(0.1)

    conn.commit()
    cursor.close()
    conn.close()
    time.sleep(0.1)

    return vecs

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

        sql="update text_table set k_means_label = null"
        cursor.execute(sql)
        time.sleep(0.1)

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

    except Exception as e:
        print(e)

if __name__=="__main__":
    project="ttt"
    desc_code="3"
    draw_elbow_func(project, desc_code)
