import MySQLdb, sys, configparser, time
from write_project_ini import write_pro_ini
from main_config import main_Config

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

    category = category_count(project, mysql_id, mysql_pass)
    label = label_count(project, mysql_id, mysql_pass)
    text = text_count(project, mysql_id, mysql_pass)

    insert_ini(project, category, label, text)

def insert_ini(project, category, label, text):
    cates=[]
    if category[0][0] == "":
        cate_no = 0
    else:
        for cate in category:
            cates.append(cate[0])
        cate_no = len(cates)

    labes=[]
    for labe in label:
        labes.append(labe[0])

    if labes[0] == "":
        labe_no = 0
    else:
        labe_no = len(labes)

    #print(cate_no, labe_no, text)

    write_pro_ini(project).main(
    nums_of_category = str(cate_no),
    nums_of_label = str(labe_no),
    count_texts_all = str(text),
    count_texts_analysis = str(text),
    sample = "0"
    )

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

        time.sleep(0.1)

        sql="select category_name, count(category_name) from text_table group by category_name"
        cursor.execute(sql)

        category=cursor.fetchall()

        time.sleep(0.1)

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

        return category

    except Exception as e:
        print(e)

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

        time.sleep(0.1)

        sql="select label_name, count(label_name) from text_table group by label_name"
        cursor.execute(sql)

        label=cursor.fetchall()

        time.sleep(0.1)

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

        #print(label)

        return label

    except Exception as e:
        print(e)

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

        time.sleep(0.1)

        sql="select count(*) from text_table"
        cursor.execute(sql)

        text=cursor.fetchone()
        text=text[0]

        time.sleep(0.1)

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

        return text

    except Exception as e:
        print(e)

if __name__=="__main__":
    project="ggt"
    count_main(project)
