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, disc_code, 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, disc_code)
    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:
        conn=MySQLdb.connect(db=project, user=mysql_id, passwd=mysql_pass, charset="utf8mb4")
        cursor=conn.cursor()

        sql="select k_means_label, count(*) from text_table where disc_code = 3 group by k_means_label"
        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 k_means_label = %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, disc_code):
    try:
        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

    except Exception as e:
        print(e)

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="ok"
    disc_code="3"
    count="10"
    k_means_func(project, disc_code, count)
