<?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 Application\Admin\Form\Exception\TranslationFieldException;
use Application\Core\Model\Language;
use Pongho\Form\Subject\SubjectInterface;

class TranslationFieldset extends PanelFieldset
{
    /**
     * @var \Application\Core\Model\Language
     */
    protected $language;

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

    /**
     * Imposta la lingua del pannello
     *
     * @return $this
     */
    public function setLanguage(Language $language)
    {
        $this->language = $language;

        return $this;
    }

    /**
     * @return Language
     */
    public function getLanguage()
    {
        return $this->language;
    }

    /**
     * {@inheritdoc}
     */
    public function handle(array $request)
    {
        /**
         * @var \Application\Admin\Form\TranslatableInterface    $model
         */
        if (!isset($request['model'])) {
            throw new \InvalidArgumentException('Parameter "model" is required!');
        }

        $model = $request['model'];

        /**
         * Salvo i possibili RelFieldset inclusi nel pannello delle traduzioni
         *
         * @var \Pongho\Form\Fieldset $field
         */
        foreach ($this->getFieldsAsHash() as $field) {
            $field->handle($request);
        }

        /**
         * Risolvo un problema riguardante il valore dei campi se questi non vengono passati nella richiesta (es. checkbox e select multiple)
         *
         * @var \Pongho\Form\Field $field
         */
        foreach ($this->getFieldsAsHash() as $field) {
            if (!isset($request[$field->getKey()])) {
                $request[$field->getKey()] = $field->emptyValue();
            }
        }

        /** @var SubjectInterface $translation_subject */
        $translation_subject = $this->getSubject();

        try {
            $translation_subject->save();

            if (!$model->setTranslation($this->language->id, $translation_subject->getProperties())) {
                $this->getForm()->addError($this->language->name, 'failed_save_translation');
            }
        } catch (TranslationFieldException $translationFieldException) {
            $this->getForm()->addError(
                $translationFieldException->getField(),
                $translationFieldException->getMessage()
            );
        }

        // Gestisco eventuali RelFieldset all'interno delle traduzioni
        if (!$this->getForm()->hasErrors()) {
            $this->handleRelsCallback($request);
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getSubject()
    {
        return $this->getParent()->getSubject()->get($this->getKey());
    }

    /**
     * {@inheritdoc}
     */
    public function getStartCode()
    {
        $panel = $this->getPanel($this->getKey());

        return sprintf(
            '<div class="tabsPanel translation-%3$s" id="%1$s" data-culture="%2$s">',
            $panel->getPrefix() . '_' . $panel->getTabName(),
            $this->language->culture,
            $this->language->id
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getEndCode()
    {
        return '</div>';
    }
}
