package ui

import "../core"
import "../shared"

App_Controller :: struct {
	state: core.Comic_State,
	active_screen: App_Screen,
	jobs: Job_Manager,
}

new_controller :: proc(state: core.Comic_State) -> App_Controller {
	screen := screen_from_workflow(state.workflow.current_step)
	return App_Controller{
		state = state,
		active_screen = screen,
		jobs = new_job_manager(),
	}
}

navigate_to_screen :: proc(c: ^App_Controller, target: App_Screen) -> shared.App_Error {
	if !can_open_screen(c.state, target) {
		return shared.new_error(.Validation, "screen blocked by workflow guards", false)
	}
	c.active_screen = target
	return shared.ok()
}

set_workflow_step :: proc(c: ^App_Controller, next: core.Workflow_Step) -> shared.App_Error {
	curr := c.state.workflow.current_step
	if !core.can_transition(curr, next) && curr != next {
		return shared.new_error(.Validation, "invalid workflow transition", false)
	}
	core.set_workflow_step(&c.state, next)
	c.active_screen = screen_from_workflow(next)
	return shared.ok()
}

start_background_job :: proc(c: ^App_Controller, t: Job_Type, message: string) -> int {
	id := submit_job(&c.jobs, t, message)
	c.state.workflow.is_generating = true
	c.state.workflow.generation_progress = 0
	c.state.workflow.error_message = ""
	return id
}

set_generation_progress :: proc(c: ^App_Controller, progress: f32) {
	c.state.workflow.generation_progress = progress
}

finish_background_job :: proc(c: ^App_Controller, id: int, failed_message: string) -> shared.App_Error {
	if len(failed_message) > 0 {
		_ = mark_job_failed(&c.jobs, id, failed_message)
		c.state.workflow.error_message = failed_message
		c.state.workflow.is_generating = false
		return shared.new_error(.Generation, failed_message, true)
	}

	_ = mark_job_completed(&c.jobs, id)
	if active_jobs_count(c.jobs) == 0 {
		c.state.workflow.is_generating = false
		c.state.workflow.generation_progress = 100
	}
	return shared.ok()
}

cancel_background_job :: proc(c: ^App_Controller, id: int) -> shared.App_Error {
	err := request_job_cancel(&c.jobs, id)
	if !shared.is_ok(err) {
		return err
	}
	if active_jobs_count(c.jobs) == 0 {
		c.state.workflow.is_generating = false
	}
	return shared.ok()
}
