import MySQLdb, sys, configparser, time, codecs

from main_config import main_Config

def csv_to_mysql(project, text_column_no, category_column_no, label_column_no):

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

    #print(project, text_column_no, category_column_no, label_column_no)

    g = codecs.open("encode_temp.txt","r","utf-8")
    texts=g.readlines()
    g.close()

    text_column_no = int(text_column_no)
    category_column_no = int(category_column_no)
    label_column_no = int(label_column_no)

    csv_data=[]
    for n in texts:
        n = n.split(",")
        a = text_column_no-1
        #print(n[0])
        if n[0]=="\n":
            pass
        else:
            text = n[a]
            text=text.replace("\n","")

            if label_column_no > 0:
                label = n[label_column_no - 1]
            else:
                label = ""

            if category_column_no > 0:
                category = n[category_column_no - 1]
            else:
                category=""

            value=(category, label, text)
            csv_data.append(value)
    #print(csv_data)

    csv_database(project, mysql_id, mysql_pass, csv_data)

    time.sleep(0.1)

    g = codecs.open("encode_temp.txt","w", "utf-8")
    g.write("")
    g.close()

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

        time.sleep(0.1)

        sql="insert into text_table(category_name, label_name, original_sentence) values (%s, %s, %s)"
        cursor.executemany(sql, import_data)

        time.sleep(0.1)

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

        #print("テーブル作成OK")

    except Exception as e:
        print(e)


if __name__=="__main__":
    project="only_text"
    text_column_no = "2"
    category_column_no = "0"
    label_column_no = "1"

    csv_to_mysql(project, text_column_no, category_column_no, label_column_no)
