<?php

namespace Application\Service\Extension\ValidatorV2;

use Application\Service\Exceptions\InvalidArgumentException;
use Application\Service\Extension\ValidatorV2\exceptions\InvalidValidatorArgumentException;

class RulesContainer
{
    /**
     * 原始规则
     * @var array
     */
    public array $originRules = [];

    /**
     * 处理后的规则
     * @var array
     */
    public array $rules = [];

    /**
     * 字段名
     * @var string
     */
    public string $label = '';

    /**
     * @var Validator|null
     */
    private ?Validator $validator = null;

    public function execute($field,$isError = 0)
    {
        $errors = [];
        try {
          $validator = $this->getValidator();
          foreach ($this->rules as $rule) {
              $method = $rule['method'];
              $attrs = $rule['attr'];
              $message = $rule['message'] ?? '';
              $v = $validator->{$method}($field);
              foreach ($attrs as $key => $item) {
                  $v->{$key}($item)->message($message);
              }
          }

          if (!$validator->isValid()) {
              if($isError == 1){
                  $errors[] = $validator->getError();
                  return $errors;
              }else{
                  //暂时不做强制控制，只提醒
                  throw new InvalidArgumentException($validator->getError());
              }
          }

          return true;
        } catch (\Throwable $exception) {
            if ($exception instanceof InvalidArgumentException) {
                throw new InvalidArgumentException($exception->getMessage());
            } else {
                return true;
            }
        }
    }

    private function getValidator(): Validator
    {
        if ($this->validator === null) {
            $this->validator = new Validator();
        }

        return $this->validator;
    }

    public function setAttributes(array $attr)
    {
        $this->getValidator()->setAttributes($attr);
    }

    public function setAttributeLabel(array $labels)
    {
        $this->getValidator()->setAttributeLabels($labels);
    }
}