<?php

namespace DefStudio\GameEngine\Http\Livewire\Runs;

use Illuminate\Contracts\View\View;
use DefStudio\GameEngine\Models\Run;
use Illuminate\Support\Facades\Gate;
use LivewireUI\Modal\ModalComponent;
use DefStudio\GameEngine\Models\Mission;
use DefStudio\GameEngine\Decorators\Runs\PlayableMission;
use DefStudio\GameEngine\Http\Livewire\Concerns\ImprovedModal;
use DefStudio\GameEngine\Http\Livewire\Runs\Concerns\RunsTasks;
use DefStudio\GameEngine\Http\Livewire\Concerns\CallsTraitsMethods;
use DefStudio\GameEngine\Http\Livewire\Runs\Concerns\RunsStorytellings;

/**
 * @property-read Run $run;
 * @property-read PlayableMission $mission
 */
class MissionModal extends ModalComponent
{
    use ImprovedModal;
    use RunsStorytellings;
    use CallsTraitsMethods;
    use RunsTasks;

    public int $run_id;

    public int $mission_id;

    protected bool $inline_storytellings = true;

    protected $listeners = [
        'complete_storytelling',
    ];

    public function mount(): void
    {
        Gate::authorize('play', $this->run);
    }

    public function getRunProperty(): Run
    {
        return Run::findOrFail($this->run_id);
    }

    public function getMissionProperty(): PlayableMission
    {
        return PlayableMission::build(Mission::findOrFail($this->mission_id))->setup($this->run);
    }

    public function render(): View
    {
        return view('game-engine::livewire.runs.mission-modal');
    }

    public function start(): void
    {
        if (!$this->is_task_active()) {
            $this->next_task();
        }
    }

    protected function complete_mission(): void
    {
        $this->emit('complete_mission');
    }
}
