<?php

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

namespace Application\Admin\Widgets;

class WidgetsCollection implements \IteratorAggregate
{
    /**
     * @var WidgetInterface[]
     */
    protected $widgets = [];

    /**
     * Permette di aggiungere un nuovo widget alla collezione.
     *
     * @return $this
     */
    public function add(WidgetInterface $widget)
    {
        $this->widgets[$widget->getKey()] = $widget;

        return $this;
    }

    /**
     * @param null|string     $pos
     * @return $this
     */
    public function addAfter(WidgetInterface $widget, $pos = null)
    {
        $new = [];

        // first position?
        if (null === $pos) {
            $new[$widget->getKey()] = $widget;
        }

        foreach ($this->widgets as $key => $value) {
            $new[$key] = $value;

            // after $pos
            if ($key === $pos) {
                $new[$widget->getKey()] = $widget;
            }
        }

        $this->widgets = $new;

        return $this;
    }

    /**
     * Indica se esiste un widget con la chiave passata.
     *
     * @param string $key
     * @return bool
     */
    public function has($key)
    {
        return isset($this->widgets[$key]);
    }

    /**
     * Restituisce un widget in base alla chiave passata.
     *
     * @param string $key
     * @return WidgetInterface
     */
    public function get($key)
    {
        if (isset($this->widgets[$key])) {
            return $this->widgets[$key];
        }

        throw new \InvalidArgumentException();
    }

    /**
     * Rimuove un widget dalla collezione.
     *
     * @param string $key
     * @return $this
     */
    public function del($key)
    {
        unset($this->widgets[$key]);

        return $this;
    }

    /**
     * @return WidgetInterface[]
     */
    public function all()
    {
        return $this->widgets;
    }

    /**
     * @return $this
     */
    public function clear()
    {
        $this->widgets = [];

        return $this;
    }

    /**
     * Renderizza la struttura del widget.
     *
     * @return string
     */
    public function render()
    {
        $code = '';
        foreach ($this->widgets as $widget) {
            $key = $widget->getKey();

            $code .= <<<HTML
<div class="widget-column{$widget->getColumns()}">
    <div class="widget" id="widget-{$key}" data-key="{$key}">
        <h3>{$widget->getTitle()}</h3>
        <div class="widget-content">{$widget->getContent()}</div>
    </div>
</div>
HTML;
        }

        return '<div class="widgets">' . $code . '</div>';
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator(): \Traversable
    {
        return new \ArrayIterator($this->widgets);
    }
}
