<?php

namespace KupShop\AdminBundle\AdminRegister;

use Symfony\Component\DependencyInjection\ServiceLocator;

class AdminRegisterLocator
{
    private bool $dynamicPermissionsIsSet = false;
    private bool $dynamicMenuIsSet = false;
    private array $activityLogTags;

    /**
     * AdminRegisterLocator constructor.
     *
     * @param string[] $dynamicRegistrations
     */
    public function __construct(
        private array $permissions,
        private array $menu,
        private readonly ServiceLocator $locator,
        private readonly array $dynamicRegistrations,
    ) {
    }

    public function getPermissions(string $type): ?array
    {
        if (!$this->dynamicPermissionsIsSet) {
            foreach ($this->dynamicRegistrations as $class) {
                /** @var IAdminRegisterDynamic $obj */
                $obj = $this->locator->get($class);
                foreach ($obj->getDynamicPermissions() as $arr) {
                    $permissionType = $arr['type'];
                    unset($arr['type']);
                    $this->permissions[$permissionType] = $arr;
                }
            }
            $this->dynamicPermissionsIsSet = true;
        }

        return $this->permissions[$type] ?? null;
    }

    public function getMenu(): array
    {
        if (!$this->dynamicMenuIsSet) {
            foreach ($this->dynamicRegistrations as $class) {
                /** @var IAdminRegisterDynamic $obj */
                $obj = $this->locator->get($class);
                foreach ($obj->getDynamicMenu() as $arr) {
                    $this->menu[$arr['menu']][] = $arr['item'];
                }
            }
            $this->dynamicMenuIsSet = true;
        }

        return $this->menu;
    }

    public function getActivityLogTags(): array
    {
        if (!isset($this->activityLogTags)) {
            $this->activityLogTags = [];
            foreach ($this->dynamicRegistrations as $class) {
                /** @var IAdminRegisterDynamic $obj */
                $obj = $this->locator->get($class);
                $this->activityLogTags = array_merge($this->activityLogTags, $obj->getActivityLogTags());
            }
        }

        return $this->activityLogTags;
    }
}
