<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;
use App\Http\Traits\BoardTrait;
use App\Rules\NormalString;
use App\Rules\FilterSpamKeyword;
use App\Rules\BlobDataEscape;

class CommentRequest extends FormRequest
{
    use BoardTrait;

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $boardID = $this->post('bid');
        $commentID = $this->post('cid');
        $boardMeta = $this->boardMeta;

        $rules = [
            'bid' => 'required|exists:tb_board,id',
            'pid' => 'required|exists:tb_post,id',
            'content' => ['required', new FilterSpamKeyword],
            'is_secret' => 'nullable|numeric|in:0,1'
        ];

        if($commentID) {
            $rules['cid'] = 'required|exists:tb_comment,id';
        }

        if(($commentMinLength = $boardMeta->item('comment_min_length', 0)) > 0) {
            $rules['content'][] = "min:$commentMinLength";
        }

        if(($commentMaxLength = $boardMeta->item('comment_max_length', 0)) > 0) {
            if($boardMeta->item('use_personal', 0)) {
                $rules['content'][] = new BlobDataEscape($boardID);
            }else{
                $rules['content'][] = "max:$commentMaxLength";
            }
        }

        // 비회원 유효성 검사
        if(!$this->user()) {
            $rules['username'] = ['required', 'min:2', 'max:10', 'string', new NormalString];
            $rules['password'] = 'required|min:3|max:10';
        }

        return $rules;
    }

    /**
     * Get custom attributes for validator errors.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'bid' => '게시판 PK',
            'pid' => '게시글 PK',
            'username' => '이름',
            'password' => '비밀번호',
            'content' => '댓글',
            'is_secret' => '비밀글'
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'username.required' => '이름을 입력하세요.',
            'username.min' => '이름은 :min자 이상 입력하세요.',
            'username.max' => '이름은 :max자 이하 입력하세요.',
            'username.string' => '이름 형식이 옳지 않습니다.',
            'password.required' => '비밀번호를 입력하세요.',
            'password.min' => '비밀번호는 :min자 이상 입력하세요.',
            'password.max' => '비밀번호는 :max자 이하 입력하세요.',
            'content.required' => '댓글을 입력해주세요.',
            'content.max' => ':attribute은 최대 :max 글자 입력 가능합니다.',
            'is_secret.in' => '비밀글은 0 또는 1 값만 허용됩니다.'
        ];
    }

   /**
     * Handle a failed validation attempt.
     *
     * @param  \Illuminate\Contracts\Validation\Validator  $validator
     * @return void
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    protected function failedValidation(Validator $validator)
    {
        if($this->wantsJson()) {
            $errors = (new ValidationException($validator))->errors();

            foreach($errors as $err) {
                throw new HttpResponseException(
                    response()->json([
                        'message' => $err
                    ], JsonResponse::HTTP_OK)
                );
            }
        }

        parent::failedValidation($validator);
    }
}
