from analyst_klondike.state.app_dispatch import app_dispatch
from analyst_klondike.features.code.actions import RunCodeAndSetResultsAction
from analyst_klondike.features.code.selector import has_failed_cases
from analyst_klondike.features.current.selectors import select_current_task
from analyst_klondike.features.events.event_hook import send_event

from analyst_klondike.state.app_state import select


def run_code_command():
    """Macro command to run code"""

    app_dispatch(RunCodeAndSetResultsAction())
    is_failed = select(has_failed_cases)
    selected_task = select(select_current_task)
    if selected_task is None:
        raise ValueError("No selected task")
    send_event("run_code", "/", event_json={
        'is_passed': not is_failed,
        'task_id': selected_task.id,
        'task_title': selected_task.title
    })
