import MySQLdb, time, configparser
from numpy import array
import numpy as np
from sklearn.cluster import KMeans
from main_config import main_Config

def k_means_func(project, word, count):
#    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, word)
    time.sleep(0.1)

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

    res = get_k_means_label(vectors, count)
    time.sleep(0.1)

    export_to_sql(project,mysql_id,mysql_pass, res)
    time.sleep(0.1)

    result=count_k_means_label(project,mysql_id,mysql_pass)
    time.sleep(0.1)

    return result

def count_k_means_label(project,mysql_id,mysql_pass):
    try:
        cfg=configparser.ConfigParser()
        file_path = project + ".ini"
        cfg.read(file_path)
        sample=cfg['project']["sample"]

        conn=MySQLdb.connect(db=project, user=mysql_id, passwd=mysql_pass, charset="utf8mb4")
        cursor=conn.cursor()
        if sample == "0":
            sql="select correlation, count(*) from text_table group by correlation"
        elif sample == "1":
            sql="select correlation, count(*) from text_table where sampling = " + sample + " group by correlation"
        else:
            sql="select correlation, count(*) from text_table where train_test_data = '1' group by correlation"
#        print(sql)
        cursor.execute(sql)
        vecs=list(cursor.fetchall())
        time.sleep(0.1)

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

    except Exception as e:
        print(e)

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

        sql="update text_table set correlation = %s where sentence_id = %s"
        cursor.executemany(sql,res)
        time.sleep(0.1)

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

    except Exception as e:
        print(e)

def get_k_means_label(vectors, count):
    li=[]
    num=[]
    for i,j in vectors:
        li.append(j)
        num.append(i)
    features =array(li)

    kmeans_model = KMeans(n_clusters=int(count), random_state=10).fit(features)#クラスター数を入力
    labels = kmeans_model.labels_
    labe=list(labels)
    res=list(zip(labe,num))
    return res

def get_array(vecs, using_os):
    vectors=[]
    for vec in vecs:
        #print(vec)
        sentence_id=vec[0]
        vec=(vec[1])
        vec=vec.split(" ")
        #print(len(vec))
        sen_vector=[]
        for ve in vec:
            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)

        sen_id_vector=(sentence_id,sen_vector)
        vectors.append(sen_id_vector)
    return vectors

def import_from_sql(project,mysql_id,mysql_pass, word):
    cfg=configparser.ConfigParser()
    file_path = project + ".ini"
    cfg.read(file_path)
    sample=cfg['project']["sample"]


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

    if sample == "0":
        sql="select sentence_id, sentence_vector from text_table where morpheme like '% " + word + " %'"
    elif sample == "1":
        sql="select sentence_id, sentence_vector from text_table where sampling = " + sample + " and morpheme like '% " + word + " %'"
    else:
        sql="select sentence_id, sentence_vector from text_table where train_test_data = '1' and morpheme like '% " + word + " %'"

    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 correlation = null"
        cursor.execute(sql)
        time.sleep(0.1)

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

    except Exception as e:
        print(e)

if __name__=="__main__":
    project="ok"
    disc_code="3"
    count="10"
    k_means_func(project, disc_code, count)
