import hashlib
from db.fz_data import getConn


def Check(username: str, password: str) -> bool:
    password_hash = hashlib.md5(password.encode()).hexdigest()
    "检查用户密码"
    sql = """
    SELECT * FROM `table_user` WHERE username = %s and password = %s;
    """
    conn = getConn()
    cursor = conn.cursor()
    try:
        cursor.execute(sql, (username, password_hash))
        results = cursor.fetchone()
        conn.close()
    except:
        conn.close()
        return False
    if results != None:
        return True
    return False


def UpdatePassword(username: str, password: str) -> bool:
    password_hash = hashlib.md5(password.encode()).hexdigest()
    "更新用户密码"
    sql = """
    UPDATE `table_user` SET `password` = %s WHERE `username` = %s;
    """
    conn = getConn()
    cursor = conn.cursor()
    try:
        c_row = cursor.execute(sql, (password_hash, username))
        conn.commit()
        conn.close()
    except:
        conn.close()
        return False
    if c_row > 0:
        return True
    return False


def New(username: str, password: str) -> bool:
    password_hash = hashlib.md5(password.encode()).hexdigest()
    "更新用户密码"
    sql = """
    INSERT INTO `table_user` (`username`, `password`) VALUES (%s, %s);
    """
    conn = getConn()
    cursor = conn.cursor()
    try:
        c_row = cursor.execute(sql, (username,password_hash))
        conn.commit()
        conn.close()
    except:
        conn.close()
        return False
    if c_row > 0:
        return True
    return False


def total() -> int:
    "返回数据库总条目数量"
    sql = """
    SELECT COUNT(*) AS total_count FROM table_user;
    """
    conn = getConn()
    cursor = conn.cursor()
    try:
        cursor.execute(sql)
        results = cursor.fetchone()
    except:
        conn.close()
        return None
    conn.close()

    return results[0]


def list():
    "返回数据库所有条目"
    sql = """
    SELECT * FROM table_user;
    """
    conn = getConn()
    cursor = conn.cursor()
    try:
        cursor.execute(sql)
        results = cursor.fetchall()
    except:
        conn.close()
        return None
    conn.close()
    return results


def Del(username: str) -> bool:
    "删除用户"
    sql = """
    DELETE FROM `table_user` WHERE `username` = %s;
    """
    conn = getConn()
    cursor = conn.cursor()
    try:
        c_row = cursor.execute(sql, (username))
        conn.commit()
        conn.close()
    except:
        conn.close()
        return False
    if c_row > 0:
        return True
    return False
