<?php

namespace Daylight\Core\Modules\MenuBuilder;

use Daylight\Core\Modules\Admin\Entities\Page;
use Daylight\Core\Modules\Admin\Registries\NavigationRegistry;
use Daylight\Core\Modules\MenuBuilder\Events\MenuUpdated;
use Daylight\Core\Modules\MenuBuilder\Listeners\ClearNavigationCache;
use Daylight\Core\Modules\MenuBuilder\Livewire\MenuTable;
use Daylight\Core\Modules\MenuBuilder\Registries\MenuRegistry;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;

class MenuBuilderServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(MenuRegistry::class, function () {
            return new MenuRegistry;
        });

        NavigationRegistry::addPage(
            Page::create()
                ->setParent('content')
                ->setKey('menus')
                ->setLabel('daylight::content.menus')
                ->setIcon('o-document-duplicate')
                ->setPermission('read:pages')
                ->setRoute('daylight.content.menus.index')
                ->setOrder(300)
        );

        NavigationRegistry::addPage(
            Page::create()
                ->setParent('settings')
                ->setKey('menus')
                ->setLabel('daylight::settings.navigation')
                ->setPermission('read:menus')
                ->setRoute('daylight.settings.navigation.index')
                ->setOrder(100)
        );
    }

    public function boot(MenuRegistry $menuRegistry): void
    {
        $this->registerLivewireComponents();

        Event::listen(MenuUpdated::class, ClearNavigationCache::class);
    }

    public function registerLivewireComponents(): self
    {
        if (! class_exists(Livewire::class)) {
            return $this;
        }

        Livewire::component('menu-table', MenuTable::class);

        return $this;
    }
}
