from datetime import datetime
from typing import Optional

import typer
from sqlalchemy.orm.exc import UnmappedInstanceError
from sqlmodel import Session, select

from .database import engine
from .functions_aux import Status
from .tables import ToDo, Timer

app = typer.Typer()


@app.command()
def task(id: str, task: str = None,
         status: Optional[Status] = typer.Option(None),
         tag: str = None, remarks: str = None, project: str = None,
         due_date: datetime = typer.Option(None, formats=['%Y-%m-%d']),
         reminder: datetime = typer.Option(None, formats=['%Y-%m-%d'])):
    """Edit record from to-do list"""
    with Session(engine) as session:
        try:
            query = session.get(ToDo, id)

            if task is not None:
                query.task = task
            if tag is not None:
                query.tag = tag
            if remarks is not None:
                query.remarks = remarks
            if project is not None:
                query.project = project

            if status is None or status == query.status:
                pass
            elif status == 'done':
                query.status = status
                query.date_end = datetime.now().date()
            elif status == 'doing' and query.status == 'done':
                query.status = status
                query.date_end = None
            elif status == 'to do':
                timer = session.exec(