from package.data.init import ensure_db_ready, get_conn
from package.entity.project import Project


@ensure_db_ready
def add_project(project: Project):
    sql = "insert into projects(project_name,project_status,fatigue_rate,fatigue_total) values(?,?,?,?)"
    with get_conn() as conn:
        cursor = conn.cursor()
        cursor.execute(
            sql,
            (
                project.project_name,
                project.project_status,
                project.fatigue_rate,
                project.fatigue_total,
            ),
        )

    return cursor.lastrowid


@ensure_db_ready
def update_project_status(project: Project):
    sql = "update projects set project_status = ? where id = ?"
    with get_conn() as conn:
        cursor = conn.cursor()
        cursor.execute(
            sql,
            (
                project.project_status,
                project.id,
            ),
        )
        conn.commit()


@ensure_db_ready
def get_project_id(id: int):
    sql = "select id,project_name,fatigue_rate,fatigue_total,project_status from projects where id = ?"
    with get_conn() as conn:
        cursor = conn.cursor()
        cursor.execute(
            sql,
            (id,),
        )

        return Project(**dict(cursor.fetchone()))


@ensure_db_ready
def get_project_name(project_name):
    sql = "select id,project_name,fatigue_total,fatigue_rate,project_status from projects where project_name = ?"
    with get_conn() as conn:
        cursor = conn.cursor()
        cursor.execute(
            sql,
            (project_name,),
        )
        row = cursor.fetchone()
        if not row:
            return None

        return Project(**dict(row))


@ensure_db_ready
def get_all_projects():
    sql = (
        "select id,project_name,fatigue_total,fatigue_rate,project_status from projects"
    )
    with get_conn() as conn:
        cursor = conn.cursor()
        cursor.execute(
            sql,
        )
        rows = cursor.fetchall()
        if not rows:
            return None

        results = []
        for r in rows:
            results.append(Project(**dict(r)))
        return results


# @ensure_db_ready
# def get_like_projects(keyname):
#     sql = "select id,project_name,fatigue_total,fatigue_rate,project_status from projects like ?%"
#     with get_conn() as conn:
#         cursor = conn.cursor()
#         cursor.execute(sql, (keyname,))
#         rows = cursor.fetchall()
#         if not rows:
#             return None

#         results = []
#         for r in rows:
#             results.append(Project(**dict(r)))
#         return results
