<?php

namespace App\Core\Validator\User;

use App\Core\Repository\User\UserRepository;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Translation\Translator;

use App\Core\Validator\BaseValidator;

use Exception;

class UserCreateValidator extends BaseValidator
{
    private $userRepository;

    public function __construct
    (
        UserRepository $userRepository,
        Translator $translator,
        Container $container
    )
    {
        parent::__construct($translator, $container);
        $this->userRepository = $userRepository;
    }

    public function rules($params = null)
    {
        return
            [
                'name' => 'required|min:3|max:150',
                'email' => 'required|email',
                'isUniqueEmail' => 'accepted',
                'password' => 'required|max:20'
            ];


    }

    public function messages()
    {
        $thisMessages = [];
        return array_merge(parent::messages() , $thisMessages);
    }

    public function isUniqueEmail($email)
    {
        try {
            $criteria =
                [
                    "criteria" =>
                        [
                            ["field" => "email", "condition" => "=", "value" => $email]
                        ]
                ];
            $result = $this->userRepository->findByCriteria($criteria);

            return $result ? false : true;

        } catch (Exception $e) {
            return false;
        }

    }

    public function validate(array $params, array $rules = [], array $messages = [], array $customAttributes = [])
    {
        $params["isUniqueEmail"] = $this->isUniqueEmail($params["email"]);
        return $this->make($params, $this->rules($params), $this->messages());
    }

}
