<?php

namespace DefStudio\GameEngine\Http\Livewire\Runs;

use Livewire\Component;
use Illuminate\Contracts\View\View;
use DefStudio\GameEngine\Enums\Role;
use DefStudio\GameEngine\Models\Run;
use Barryvdh\Debugbar\Facades\Debugbar;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use DefStudio\GameEngine\Http\Livewire\Runs\Concerns\RunsMaps;
use DefStudio\GameEngine\Http\Livewire\Runs\Concerns\RunsStory;
use DefStudio\GameEngine\Http\Livewire\Runs\Concerns\RunsMissions;
use DefStudio\GameEngine\Http\Livewire\Concerns\CallsTraitsMethods;
use DefStudio\GameEngine\Http\Livewire\Runs\Concerns\RunsStorytellings;

/**
 * @property-read Run $run
 */
class Runner extends Component
{
    use AuthorizesRequests;
    use RunsStorytellings;
    use RunsStory;
    use RunsMaps;
    use RunsMissions;
    use CallsTraitsMethods;

    protected $listeners = [
        'next_mission',
        'complete_mission',
        'complete_storytelling',
    ];

    public int $run_id;

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

    }

    public function render(): View
    {
        Debugbar::disable();

        return view('game-engine::livewire.runs.runner');
    }

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

    public function reset_run(): void
    {
        abort_unless(game_engine()->user()->hasRole(Role::super_admin->value), 403);

        $this->run->state = [];
        $this->run->completed_at = null;
        $this->save();

        $this->reload_page();
    }

    protected function reload_page(): void
    {
        $this->redirect(route('game-engine.play', $this->run->story));
    }

    protected function save(): void
    {
        $this->run->save();
    }
}
