import configparser, os, MySQLdb, time, subprocess, codecs
from main_config import main_Config

def evaluation(project):
#    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()

    labels = import_test_data(project, mysql_id, mysql_pass, using_os)
    rate = test(project, labels)

    #path=os.getcwd()
    #path=path + "/for_test_temp.txt"
    #os.remove(path)
    time.sleep(0.1)
    for_temp_path=os.getcwd()
    for_temp_path=for_temp_path + "/for_test_temp.txt"
    time.sleep(0.1)
    if os.path.isfile(for_temp_path):
        os.remove(for_temp_path)

    return str(round(rate * 100))


def import_test_data(project, mysql_id, mysql_pass, using_os):
    g = open("for_test_temp.txt","w")
    g.write("")
    g.close()
    try:
        conn=MySQLdb.connect(db=project, user=mysql_id, passwd=mysql_pass, charset="utf8mb4")
        cursor=conn.cursor()

        sql="select label_name, morpheme from text_table where train_test_data = 2"

        cursor.execute(sql)
        nums=list(cursor.fetchall())

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

        labels=[]

        g = codecs.open("for_test_temp.txt","w", "utf-8")
        for n in nums:
            labels.append(n[0])
            content=n[1]
            g.write(content)
            if using_os =="nt":
                g.write("\n")
            elif using_os == "posix":
                g.write("\n")
        g.close()

        return labels

    except Exception as e:
        print(e)


def test(project, labels):
    path = os.getcwd()
    cmd= path + "/fastText/fasttext predict-prob " + path + "/fastText/" + project + ".bin " + path + "/for_test_temp.txt"
    proc = subprocess.Popen(cmd, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
    stdout_data, stderr_data = proc.communicate() #処理実行を待つ(†1)
    #print(stdout_data)  #標準出力の確認
    #print(stderr_data)  #標準エラーの確認
    proc.wait()
    stdout_data = stdout_data.decode("utf-8")
    stdout_data = stdout_data.split("\n")

    test_data=[]
    for n in stdout_data:
        if n == "":
            pass
        else:
            test_data.append(n)

    test_data_count=len(test_data)

    prediction_ok = 0
    prediction_not = 0
    for (i,j) in zip(labels, test_data):
        label = i
        j=j.split(",")
        #print(j)
        res_label = j[0].replace("__label__","")
        res_prob =j[1]
        if label == res_label:
            prediction_ok += 1
        else:
            prediction_not += 1

    rate = (prediction_ok / test_data_count)
    #print(rate)

    return rate

if __name__=="__main__":
    project="ok"
    evaluation(project)
