<?php
// SPDX-FileCopyrightText: IndieHosters <contact@indiehosters.net>
// SPDX-License-Identifier: AGPL-3.0-or-later

namespace OCA\CustomNav;

use OCA\CustomNav\AppInfo\Application;
use OCP\AppFramework\Http\Events\BeforeTemplateRenderedEvent;
use OCP\AppFramework\Services\IInitialState;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\INavigationManager;
use OCA\CustomNav\Service\Manager;
use OCP\IUserSession;
use OCP\Util;

class BeforeTemplateRenderedListener implements IEventListener
{
    protected IInitialState $initialState;
    protected INavigationManager $navigationManager;
    protected Manager $manager;
    private IUserSession $userSession;

    public function __construct(
        IInitialState $initialState,
        INavigationManager $navigationManager,
        Manager $manager,
        IUserSession $userSession,
    ) {
        $this->initialState = $initialState;
        $this->navigationManager = $navigationManager;
        $this->manager = $manager;
        $this->userSession = $userSession;
    }

    public function handle(Event $event): void
    {
        if ($event instanceof BeforeTemplateRenderedEvent) {
            Util::addStyle(Application::APP_ID, "customnav");
            Util::addScript(Application::APP_ID, "customnav-main");
            $user = null;
            $overwrites = [
                $this->manager->getSystemOverwrite(),
            ];
            if (!$this->manager->isDisableUserEdit()) {
                $user = $this->userSession->getUser();
                if ($user != null) {
                    array_push($overwrites,  $this->manager->getUserOverwrite($user));
                }
            }
            $apps = $this->manager->getDefaultApps();
            $apps = $this->manager->applyOverwrites($apps, ...$overwrites);
            $this->initialState->provideInitialState("apps", $apps);
        }
    }
}
