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,fatigue_rate,fatigue_total) values(?,?,?)"
    with get_conn() as conn:
        cursor = conn.cursor()
        cursor.execute(
            sql,
            (
                project.project_name,
                project.fatigue_rate,
                project.fatigue_total,
            ),
        )

    return cursor.lastrowid


@ensure_db_ready
def get_project_id(id: int):
    sql = "select id,project_name,fatigue_rate,fatigue_total 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 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_projects():
    sql = "select id,project_name,fatigue_total,fatigue_rate 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
