from package.data.init import ensure_db_ready, get_conn
from package.entity.record import Record
from package.entity.project import Project
from datetime import datetime
import time


@ensure_db_ready
def add_record(record: Record):
    sql = "insert into records(start,stop,duration,task_desc,extra_id,project_id) values(?,?,?,?,?,?)"
    with get_conn() as conn:
        cursor = conn.cursor()
        cursor.execute(
            sql,
            (
                record.start,
                record.stop,
                record.duration,
                record.task_desc,
                record.extra_id,
                record.project_id,
            ),
        )
        conn.commit()


@ensure_db_ready
def update_stop_record(record: Record):
    sql = (
        "update records set stop = ? , duration = ? where project_id = ? and stop = -1"
    )
    with get_conn() as conn:
        cursor = conn.cursor()
        cursor.execute(
            sql,
            (
                record.stop,
                record.duration,
                record.project_id,
            ),
        )
        conn.commit()


@ensure_db_ready
def get_recent_pending_record_by_project(record: Record):
    sql = (
        "select id,start,stop,task_desc from records where stop = -1 and project_id = ?"
    )
    with get_conn() as conn:
        cursor = conn.cursor()
        cursor.execute(
            sql,
            (record.project_id,),
        )
        row = cursor.fetchone()

        if not row:
            return None

        return Record(**dict(row))


@ensure_db_ready
def get_recent_record_by_project(record: Record):
    sql = "select id,start,stop,task_desc from records where project_id = ? ORDER BY start DESC LIMIT 1"
    with get_conn() as conn:
        cursor = conn.cursor()
        cursor.execute(
            sql,
            (record.project_id,),
        )
        row = cursor.fetchone()

        if not row:
            return None

        return Record(**dict(row))


@ensure_db_ready
def get_today_accumulated_fatigue(project_id=None):
    # 截止今天0点的时间戳
    today = datetime.now().replace(hour=4, minute=0, second=0, microsecond=0)
    now_ts = int(time.time())
    today_ts = int(today.timestamp())

    sql = """
        SELECT
        p.id,
        p.project_name,
        p.fatigue_total,
        SUM(
            CASE
                WHEN r.stop = -1 then (? - start)
                ELSE r.duration
            END * p.fatigue_rate / 60
        ) AS used_fatigue,
        p.project_status
        FROM projects p
        LEFT JOIN records r ON r.project_id = p.id AND r.start >= ?

    """
    params = [now_ts, today_ts]
    if project_id:
        sql = sql + " WHERE project_id = ?"
        params.append(project_id)

    sql += " GROUP BY p.id"
    with get_conn() as conn:
        cursor = conn.cursor()
        cursor.execute(
            sql,
            tuple(params),
        )

        if project_id:
            row = cursor.fetchone()
            if row is not None:
                total_duration = row[3] if row[3] is not None else 0
                return total_duration
            else:
                return 0
        else:
            rows = cursor.fetchall()
            results = []
            for r in rows:
                results.append(
                    {
                        "id": r[0],
                        "name": r[1],
                        "total": r[2],
                        "used": r[3] if r[3] is not None else 0,
                        "status": r[4],
                    }
                )
            return results
