<?php

namespace apexl\Io\modules\menu\includes;

use apexl\Io\includes\Routes;
use apexl\Io\modules\user\enums\permissions\Common;
use apexl\Io\modules\user\interfaces\PermissionInterface;
use apexl\Io\utilityIncludes\route;

class menuItem
{
    public $name = '';
    public $title = '';
    public $href = '#';
    public PermissionInterface $permission = Common::ALLOW_ALL;
    public $icon = '';
    public $links = null;
    protected $weight = 0;
    protected $parent = false; //top level menu items don't always link. So we use this to test display when no children present.

    public function __construct($item, route $route = null)
    {
        $this->setTitle($item['title'] ?? '');
        $this->setIcon($item['icon'] ?? '');
        $this->setWeight($item['weight'] ?? 1);
        $this->setLinks($item['links'] ?? null);
        if ($route !== null) {
            $this->setPath(Routes::getRoutePattern($route->getName(), $item['replacements'] ?? []));
            $this->setName($route->getName());
            if ($permission = $route->getPermission()) {
                $this->setPermission($permission);
            }
        } else {
            $this->setPath(
                sprintf(
                    '%s%s',
                    preg_match('/^https?:\/\//', $item['routeName']) ? '' : '/',
                    $item['routeName']
                )
            );
            $this->setName($item['routeName']);
            $this->parent = true; //Assume parent link (or otherwise broken link)
        }
    }

    /**
     * @param $title
     * @return $this
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    public function setIcon($icon)
    {
        $this->icon = $icon;

        return $this;
    }

    public function setLinks($links)
    {
        $this->links = $links;

        return $this;
    }

    /**
     * @param $path
     * @return $this
     */
    public function setPath($path)
    {
        $this->href = $path;
        if (empty($this->title)) {
            $this->setTitle($this->href);
        }

        return $this;
    }

    /**
     * @param $name
     * @return $this
     */
    public function setName($name)
    {
        $this->name = str_replace('/', '.', (string) $name);

        return $this;
    }

    public function setPermission(string|PermissionInterface $permission)
    {
        if (is_string($permission)) {
            $permission = unserialize($permission);
        }

        $this->permission = $permission;

        return $this;
    }

    public function getWeight()
    {
        return $this->weight;
    }

    public function setWeight($weight)
    {
        $this->weight = $weight;

        return $this;
    }

    public function isParent()
    {
        return $this->parent;
    }
}
