from dataclasses import dataclass

from analyst_klondike.state.app_state import AppState
from analyst_klondike.state.base_action import BaseAction


@dataclass
class ToggleTaskEditMode(BaseAction):
    type = "TOGGLE_TASK_EDIT_MODEL"
    task_id: int


@dataclass
class UpdateCurrentTaskText(BaseAction):
    type = "UPDATE_CURRENT_TASK_TEXT"
    text: str


@dataclass
class UpdateTaskPythonSourceCode(BaseAction):
    type = "UPDATE_TASK_PYTHON_SOURCE_CODE"
    code: str


def apply(state: AppState, action: BaseAction) -> AppState:
    if isinstance(action, ToggleTaskEditMode):
        task = state.data.tasks[action.task_id]
        task.is_edited = not task.is_edited
    if isinstance(action, UpdateCurrentTaskText):
        if state.current.task_id is None:
            raise ValueError(
                "Fail to update current task text - no task selected"
            )

        current_task = state.data.tasks[state.current.task_id]
        current_task.description = action.text

    if isinstance(action, UpdateTaskPythonSourceCode):
        if state.current.task_id is None:
            raise ValueError(
                "Fail to update current task text - no task selected"
            )
        current_task = state.data.tasks[state.current.task_id]
        current_task.python_source_code = action.code
    return state


def select_task_is_edited(state: AppState, task_id: int) -> bool:
    task_for_id = state.data.tasks.get(task_id)
    if task_for_id is None:
        raise ValueError(f"No task with id = {task_id}")
    return task_for_id.is_edited
