<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author    Daniele Termini
 * @copyright Web Agency Meta Line S.r.l.
 * @package   Application\Admin
 */

namespace Application\Admin\AdminSidebar;

use Pongho\Menu\ItemInterface;
use Pongho\Menu\Menu;

class Panel extends Menu
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @var int|null
     */
    protected $module;

    /**
     * @var array
     */
    protected $items_map = [];

    /**
     * @param string $label
     * @param string $name
     * @param string $class
     * @param integer $module
     */
    public function __construct($label, $name, $class, $module = null)
    {
        $this->name = $name;
        $this->module = $module;

        parent::__construct($label);

        $this->addClass($class);
    }

    /**
     * {@inheritdoc}
     */
    public function add(ItemInterface $item, $pos = 0)
    {
        $item
            ->setOptions($this->getOptions())
            ->setParent($this);

        $this->items[$pos][$item->getUrl()] = $item;
        $this->items_map[$item->getUrl()] = $pos;

        return $this;
    }

    /**
     * {@inheritdoc}
     *
     * @return Item[]
     */
    public function getItems()
    {
        $items = [];

        ksort($this->items);

        foreach ($this->items as $positions) {
            foreach ($positions as $url => $item) {
                $items[$url] = $item;
            }
        }

        return $items;
    }

    /**
     * @param $url
     * @return Item
     * @throws \InvalidArgumentException
     */
    public function getItem($url)
    {
        $items = $this->getItems();

        if (array_key_exists($url, $items)) {
            return $items[$url];
        }

        throw new \InvalidArgumentException(sprintf('The item %s does not exist', $url));
    }

    /**
     * @param $url
     */
    public function removeItem($url)
    {
        if (array_key_exists($url, $this->items_map)) {
            $pos = $this->items_map[$url];
            unset($this->items_map[$url]);
            unset($this->items[$pos][$url]);
        }
    }

    /**
     * @var bool
     */
    protected $force_dropdown;

    /**
     * Forza il render di un pannello come dropdown anche se contiene un solo item
     *
     * @param bool $force
     */
    public function forceDropdown($force = true)
    {
        $this->force_dropdown = $force;
    }

    /**
     * @return bool
     */
    public function isDropdownForced()
    {
        return $this->force_dropdown;
    }
}
