from package.data.project import get_project_name, add_project, update_project_status
from package.data.record import add_record, get_recent_pending_record_by_project
from package.entity.project import Project
from package.entity.record import Record
from package.utils.utils import get_config
from datetime import datetime
import typer
import subprocess


def start(task_desc, project_name, extra_id):
    p = get_project_name(project_name)
    if not p:
        p = Project(None, project_name=project_name, project_status=1)
        p_id = add_project(p)
    else:
        p_id = p.id

    record = get_recent_pending_record_by_project(Record(id=None, project_id=p_id))
    if record:
        typer.secho("项目已经进行，请先停止", fg=typer.colors.RED, err=True)
        return
    start_time = int(datetime.today().timestamp())
    record = Record(
        None, start=start_time, task_desc=task_desc, project_id=p_id, extra_id=extra_id
    )
    add_record(record=record)
    p.project_status = 1
    update_project_status(project=p)

    config = get_config()
    if config["enable_timew"]:
        params = ["timew", "start", project_name]
        subprocess.run(params)
