<?php

namespace App\Livewire;

use App\Models\Application;
use Flux\Flux;
use Livewire\Attributes\Computed;
use Livewire\Attributes\On;
use Livewire\Component;

class AppInfoModal extends Component
{
    public Application $app;
    public ?string $name = '';
    public string $query = '';
    public ?string $icon = null;
    public ?string $redirect_uri = '';

    public function updated($prop)
    {
        if ($prop == "query") {
            if (empty($this->query)) {
                return null;
            }
            $s = str($this->query)->kebab()->toString();
            $icon = "https://cdn.jsdelivr.net/gh/selfhst/icons/webp/{$s}.webp";
            $this->icon = $icon;
        }
    }

    #[On('appinfo')]
    public function loadApp($id)
    {
        $this->app = Application::find($id);
        $this->name = $this->app->name;
        $this->icon = $this->app->getIconUrl();
        $this->redirect_uri = $this->app->redirect_uri;
    }

    public function save()
    {
        $this->app->update([
            'name' => $this->name,
            'icon' => $this->icon,
            'redirect_uri' => $this->redirect_uri,
        ]);

        $this->dispatch('app-updated', ['id' => $this->app->id]);
    }

    public function render()
    {
        return view('livewire.app-info-modal');
    }
}
