<?php

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

namespace Application\Admin\Form;

use Pongho\Core\Kernel;
use Pongho\Form\Utilities\FormBuilder as BaseBuilder; // TODO: Perché non usare quello nello stesso namespace?
use Pongho\Utilities\Inflector;

class TranslationsManagerFieldset extends PanelsManagerFieldset implements TranslationsManagerInterface
{
    /**
     * @var array
     */
    protected $panel_fields = [];

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

    /**
     * {@inheritdoc}
     */
    public function __construct($key)
    {
        parent::__construct($key, true);
    }

    /**
     * {@inheritdoc}
     */
    public function build(array $child_fields)
    {
        $this->panel_fields = $child_fields;
    }

    /**
     * {@inheritdoc}
     */
    public function afterAddFieldToParent()
    {
        $module_languages = $this->getSetting('languages');

        /** @var \Application\Admin\Form\Subject\TranslationsSubject $translations */
        $translations = $this->getSubject();

        /** @var \Pongho\Form\Subject\SubjectInterface $translationSubject */
        foreach ($translations->getModel() as $language_id => $translationSubject) {
            $translation = (new TranslationFieldset($language_id))
                ->setSubject($translationSubject)
                ->setLanguage($module_languages[$language_id]);

            BaseBuilder::addFields($translation, $this->panel_fields);
            $this->add($translation);
            $translation->afterAddFieldToParent();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getStartCode()
    {
        /** @var \Application\Core\Entity\LanguageInterface[] $languages */
        $languages = $this->getSetting('languages');

        /** @var TranslationFieldset $translation */
        foreach ($this->getFields() as $translation) {
            $language = $languages[$translation->getKey()];

            $flag = sprintf(
                '<img class="flag" src="%1$s" alt="%2$s" title="%2$s" />',
                pongho_url('/Application/Core/Resources/flags/16/' . $language->getCulture() . '.png'),
                $language->getName()
            );

            $panel = $translation->getPanel($language->getCulture());
            $panel->setPrefix($this->getSetting('tab_prefix'));
            $panel->setTabLabel($flag);

            $enabled = false;
            if ($this->hasSetting('enabled_tab_callback')) {
                $enabled = call_user_func($this->getSetting('enabled_tab_callback'), $language, $translation);
            } elseif (Kernel::instance()->isDebug()) {
                throw new \LogicException(
                    'The "enabled_tab_callback" setting to enable a tab is missing in the field configuration'
                );
            }

            $this->languages[$panel->getTabName()] = [
                'id'         => $language->getId(),
                'is_enabled' => $enabled,
                'culture'    => $language->getCulture(),
                'label'      => $language->getName(),
            ];

            $this->pm->attachPanel($panel);
        }

        return parent::getStartCode();
    }

    /**
     * {@inheritdoc}
     */
    protected function getTabsCode()
    {
        $moduleLanguages = $this->getSetting('languages');

        // Renderizzo le tab
        $tabsCode = '';

        /** @var \Application\Admin\Utilities\Panel $panel */
        foreach ($this->pm->getPanels() as $panel) {
            $language = $this->languages[$panel->getTabName()];

            $active = $this->getSetting('tab_active') === Inflector::selectorize($language['culture']);

            if (count($moduleLanguages) > 1) {
                $tabsCode .= sprintf(
                    '<li%1$s%5$s id="%6$s" data-name="%7$s"><a href="%2$s" title="%3$s">%4$s</a></li>',
                    ($active ? ' class="active"' : ''),
                    $panel->getLink(),
                    $language['label'],
                    $panel->getTabLabel(),
                    ($language['is_enabled'] ? '' : ' style="display: none;"'),
                    'language-' . $language['id'],
                    $language['culture']
                );
            }
        }

        if (count($moduleLanguages) > 1) {
            // todo: Disattivo temporaneamente le vecchie tab di Pongho usando la classe "nojs"
            $tabsCode = sprintf(
                '<ul class="tabs translations nojs" data-ref="%s">%s</ul>',
                $this->getSetting('tab_prefix'),
                $tabsCode
            );
        }

        return $tabsCode;
    }

    /**
     * {@inheritdoc}
     */
    public function handle(array $request)
    {
        if (empty($request['translations']) || !is_array($request['translations'])) {
            return $this;
        }

        /** @var \Application\Cms\Model\Entity $model */
        $model = $this->getForm()->getSubject()->getModel();

        foreach ($request['translations'] as $language_id => $translation) {
            /** @var TranslationFieldset $panel */
            $panel = $this->getField($language_id);

            // Inserisco i valori dei campi mancanti
            $translation['language_id'] = $language_id;
            $translation[$model->getEntityType() . '_id'] = $model->id;
            $translation['model'] = $model;

            $panel->handle($translation);
        }

        return $this;
    }
}
