<?php

namespace Velis\Mvc\Validators\Rules;

use Velis\App;
use Velis\Lang;
use Velis\Mvc\Validators\Rules\RuleInterface;
use Velis\Filter\Validation;

class LangRequired implements RuleInterface
{
    public const APP_LANG = 'app-lang';
    public const CURRENT_LANG = 'current-lang';
    public const USER_SETTING_LANG = 'user-setting-lang';

    private string $lang;

    public function __construct($type = self::APP_LANG)
    {
        switch ($type) {
            case self::APP_LANG:
                $this->lang = Lang::getDefaultLanguage();
                break;
            case self::CURRENT_LANG:
                $this->lang = Lang::getLanguage();
                break;
            case self::USER_SETTING_LANG:
                $this->lang = App::$user['lang_id'];
                break;
            default:
                if (in_array($type, array_keys(Lang::getLanguages()))) {
                    $this->lang = $type;
                } else {
                    $this->lang = Lang::getDefaultLanguage();
                }
                break;
        }
    }

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

        $field = $this->getFieldName($fieldName);
        $validation->add($field, Validation::TYPE_PRESENCE_OF, []);

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

    public function getErrorMessage($fieldName): string
    {
        $field = $this->getFieldName($fieldName);
        return "{$field} is required";
    }

    private function getFieldName($fieldName): string
    {
        return $fieldName . '_' . $this->lang;
    }
}
