<?php

namespace apexl\Io\modules\basicDisplay;

use apexl\Io\includes\moduleStore;
use apexl\Io\modules\display\controllers\displayController;
use apexl\Io\modules\display\controllers\formsController;
use apexl\Io\modules\menu\services\Menu;
use apexl\Io\modules\user\classes\userManagedDisplayModule;

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

    public function __construct(...$args)
    {
        $this->moduleStore = moduleStore::getInstance();
        parent::__construct();
        foreach ($args as $arg) {
            if (is_subclass_of($arg, '\apexl\Io\includes\Entity')) {
                $this->moduleStore::addEntityToStore($this->getName(), $arg);
            }
        }
    }

    public function routes(): void
    {
        if ($entities = $this->moduleStore::getModuleEntities($this->getName())) {
            foreach ($entities as $entity) {
                $this->addProtectedEntityRoutes($entity, [
                    'all' => [displayController::class.':all', 'View'.$entity->getEntityName()],
                    'get' => [displayController::class.':view', 'View'.$entity->getEntityName()],
                    'put' => [displayController::class.':create', 'Update'.$entity->getEntityName()],
                    'post' => [displayController::class.':create', 'Create'.$entity->getEntityName()],
                    'delete' => [displayController::class.':delete', 'Delete'.$entity->getEntityName()],
                ]);

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

    public function registerMenuItems(Menu $menu)
    {
        if ($entities = $this->moduleStore::getModuleEntities($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');
            }
        }
    }
}
