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


def stop(project_name):
    project = get_project_name(project_name=project_name)
    if not project:
        raise ValueError("找不到项目，请重新输入")
    record_ = get_recent_pending_record_by_project(
        Record(id=None, project_id=project.id)
    )

    if record_:
        start_time = record_.start
    else:
        typer.secho("找不到正在进行的记录")
        return
    if not start_time:
        raise ValueError("找不到开始时间，请重新输入")
    stop_time = int(datetime.today().timestamp())
    duration_time = stop_time - start_time
    record = Record(
        id=None, stop=stop_time, duration=duration_time, project_id=project.id
    )
    update_stop_record(record)
    project.project_status = 0
    update_project_status(project=project)
    config = get_config()
    if config["enable_timew"]:
        params = ["timew", "stop", project_name]
        subprocess.run(params)
