<?php

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

namespace Application\Admin\Utilities;

class PanelsManager implements \Stringable
{
    protected $panels = [];

    /**
     * Aggiunge un pannello al manager
     */
    public function attachPanel(Panel $panel)
    {
        $this->panels[$panel->getTabName()] = $panel;
    }

    /**
     * Rimuove un pannello dal manager
     */
    public function detachPanel($name)
    {
        unset($this->panels[$name]);
    }

    /**
     * Restituisce il codice delle label delle tabs
     *
     * @return string
     */
    public function renderTabs()
    {
        $code = '';

        if (count($this->panels) > 1) {
            /** @var Panel $panel */
            foreach ($this->panels as $panel) {
                $code .= $panel->renderTab();
            }

            // todo: Disattivo temporaneamente le vecchie tab di Pongho usando la classe "nojs"
            return '<ul class="tabs nojs">' . $code . '</ul>';
        }

        return '';
    }

    /**
     * Restituisce il codice completo delle tabs
     *
     * @return string
     */
    public function renderPanels()
    {
        $code = '';

        foreach ($this->panels as $panel) {
            /** @var Panel $panel */
            if ($panel->getContent() !== null) {
                $code .= sprintf(
                    '<div class="tabsPanel" id="%s">%s</div>',
                    $panel->getPrefix() . '_' . $panel->getTabName(),
                    $panel->getContent()
                );
            }
        }

        return $code;
    }

    /**
     * Restituisce il codice completo delle tabs comprensivo di label
     *
     * @return string
     */
    public function render()
    {
        return $this->renderTabs() . $this->renderPanels();
    }

    /**
     * Restituisce uno specifico pannello
     *
     * @param string $name
     * @throws \DomainException
     * @return string
     */
    public function getPanel($name)
    {
        if (!array_key_exists($name, $this->panels)) {
            throw new \DomainException('The "%s" panel does not exists');
        }

        return $this->panels[$name];
    }

    /**
     * Restituisce l'array dei pannelli
     *
     * @return array
     */
    public function getPanels()
    {
        return $this->panels;
    }

    public function __toString(): string
    {
        return $this->render();
    }
}
