<?php

namespace apexl\Io\modules\basicDisplay;

use apexl\Io\includes\Entity;
use apexl\Io\includes\moduleStore;
use apexl\Io\modules\display\controllers\displayController;
use apexl\Io\modules\display\controllers\formsController;
use apexl\Io\modules\menu\interfaces\registersMenuItems;
use apexl\Io\modules\menu\services\Menu;
use apexl\Io\modules\user\classes\userManagedDisplayModule;
use apexl\Io\modules\user\enums\permissions\Common;

/**
 * Base module file, provides required methods to register things like routes and middleware.
 * Class installModule
 * @package apexl\Io\modules\install
 */
class basicDisplayModule extends userManagedDisplayModule implements registersMenuItems
{
    protected moduleStore $moduleStore;

    public function __construct(...$args)
    {
        parent::__construct();

        $this->moduleStore = moduleStore::getInstance();

        foreach (array_filter($args, fn(mixed $arg): bool => $arg instanceof Entity) as $arg) {
            $this->moduleStore->add($this->getName(), $arg);
        }
    }

    /**
     * @Todo - Refine permissions. For now, using Core ENUMs
     */
    public function routes(): void
    {
        if ($entities = $this->moduleStore->all($this->getName())) {
            foreach ($entities as $entity) {
                $this->addProtectedEntityRoutes($entity, [
                    'all' => [displayController::class . ':all', Common::VIEW],
                    'get' => [displayController::class . ':view', Common::VIEW],
                    'put' => [displayController::class . ':create', Common::UPDATE],
                    'post' => [displayController::class . ':create', Common::CREATE],
                    'delete' => [displayController::class . ':delete', Common::DELETE],
                ]);

                //add Form Route
                $this->addProtectedEntityFormRoute(
                    $entity,
                    $entity->getEntityName() . '/createUpdate[/{id}]',
                    formsController::class . ':entityCreateUpdate',
                );
            }
        }
    }

    public function menuItems(Menu $menu): void
    {
        if ($entities = $this->moduleStore->all($this->getName())) {
            foreach ($entities as $entity) {
                $menu::addToMenu($entity->getEntityName() . '.adminParent', [
                    'title' => $entity->getNiceName(),
                ], 'administration');
                $menu::addToMenu($entity->getEntityName() . '.display.all', [
                    'title' => 'View List',
                    'parent' => $entity->getEntityName() . '.adminParent',
                ], 'administration');
                $menu::addToMenu($entity->getEntityName() . '.display.post', [
                    'title' => 'Create',
                    'parent' => $entity->getEntityName() . '.adminParent',
                ], 'administration');
            }
        }
    }
}
