import time, sys, configparser, MySQLdb
from collections import Counter

def search_main_word(project,mysql_id,mysql_pass, claster, content_check, func, word):
    time.sleep(0.1)
    sentences = import_sentence(project,mysql_id,mysql_pass, claster, content_check, func, word)
    words = list_set(sentences)
    time.sleep(0.1)
    main_word_list = count(words)

    return main_word_list

def count(contents):
    counter = Counter(contents)
    main_word_list=[]
    for word, cnt in counter.most_common():
        word = word.replace("'","")
        a=(word, cnt)
        main_word_list.append(a)
    return main_word_list

def list_set(sentences):
    words=[]
    for word in sentences:
        word=str(word)
        word=word.replace("('","")
        word=word.replace("',)","")
        word=word.split(" ")

        wordb=[]
        for worda in word:
            if worda == "":
                pass
            else:
                wordb.append(worda)

        wordb=list(set(wordb))
        words.extend(wordb)

    return words

def import_sentence(project,mysql_id,mysql_pass, claster, content_check, func, word):
    if func == 0:
        if int(content_check) == 0:
            sql="select content_word from text_table where k_means_label = " + claster
        else:
            sql="select morpheme from text_table where k_means_label = " + claster
    else:
        if int(content_check) == 0:
            sql="select content_word from text_table where k_means_label = " + claster + " and content_word like '% " + word + " %'"
        else:
            sql="select morpheme from text_table where k_means_label = " + claster + " and content_word like '% " + word + " %'"

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

        cursor.execute(sql)
        sentences=list(cursor.fetchall())
        time.sleep(0.1)

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

        return sentences

    except Exception as e:
        print(e)

if __name__=="__main__":
    project="ok"
    mysql_id="kazuki"
    mysql_pass="makabe"
    claster="0"
    content_word="0"
    search_main_word(project, mysql_id, mysql_pass, claster, content_word)
