<?php

namespace Velis\Mvc\Validators\Rules;

use Velis\App;
use Velis\Filter\Validation;

class Date implements RuleInterface
{
    public const FORMAT_ISO = 'Y-m-d\TH:i:s.vp';
    private string $format;

    public function __construct(string $format = 'Y-m-d')
    {
        $this->format = $format;
    }

    public function validate(array $data, string $fieldName): bool
    {
        /** @var Validation $validation */
        $validation = App::$di->get('validation');

        $validation->add($fieldName, Validation::TYPE_DATE, [
            'format' => $this->format,
            'allowEmpty' => true
        ]);

        return $validation->validate($data)->count() === 0;
    }

    public function getErrorMessage($fieldName): string
    {
        if ($this->format === self::FORMAT_ISO) {
            return "{$fieldName} should be a date in ISO format (YYYY-MM-DDTHH:mm:ss.sssZ)";
        }

        return "{$fieldName} should be a date in {$this->format} format";
    }
}
