<?php

namespace Myvetshop\Module\Clinique\Form;

use AbstractForm;
use Animal;
use DateTime;
use FormField;
use FormFormatterInterface;
use Myvetshop\Module\Clinique\Persister\AnimalPersister;
use Smarty;
use Symfony\Component\Translation\TranslatorInterface;
use Tools;
use Validate;

class AnimalForm extends AbstractForm
{
    private $persister;

    public function __construct(Smarty $smarty, TranslatorInterface $translator, FormFormatterInterface $formatter, AnimalPersister $persister)
    {
        parent::__construct($smarty, $translator, $formatter);

        $this->persister = $persister;
    }

    public function getTemplateVariables()
    {
        if (!$this->formFields) {
            $this->formFields = $this->formatter->getFormat();
        }

        $this->setValue('token', $this->persister->getToken());

        return [
            'action' => $this->action,
            'errors' => $this->getErrors(),
            'formFields' => array_map(
                function (FormField $field) {
                    return $field->toArray();
                },
                $this->formFields
            ),
        ];
    }

    public function submit(): bool
    {
        if (!$this->validate()) {
            return false;
        }
        $animalId = Tools::getValue('id_animal');
        $animal = new Animal($animalId);

        foreach ($this->formFields as $formField) {
            $animal->{$formField->getName()} = $formField->getValue();
        }

        return $this->persister->save($animal, $this->getValue('token'));
    }

    public function validate()
    {
        $birthdateField = $this->getField('date_naissance');

        if (!is_null($birthdateField)) {
            $birthdateValue = $birthdateField->getValue();
            if (!empty($birthdateValue)) {
                if (!Validate::isBirthDate($birthdateValue)) {
                    $birthdateField->addError($this->translator->trans('La date de naissance ne peut être supérieure à la date d\'aujourd\'hui.', [], 'Modules.Myvetshopclinique.Shop'));
                } else {
                    $birthdate = DateTime::createFromFormat('Y-m-d', $birthdateValue);
                    $birthdateField->setValue($birthdate->format('Y-m-d'));
                }
            }
        }

        $rationField = $this->getField('ration');

        if (!is_null($rationField)) {
            $rationValue = (int) $rationField->getValue();
            if ($rationValue < 0) {
                $rationField->addError($this->translator->trans('La valeur de la ration n\'est pas valide.', [], 'Modules.Myvetshopclinique.Shop'));
            } else {
                $rationField->setValue($rationValue);
            }
        }

        return parent::validate();
    }
}
