<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_MpPayPal
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\MpPayPal\Gateway\Validator;

use Magento\Payment\Gateway\Validator\AbstractValidator;
use Webkul\MpPayPal\Gateway\Helper\SubjectReader;
use Magento\Payment\Gateway\Validator\ResultInterfaceFactory;

class GeneralResponseValidator extends AbstractValidator
{
    /**
     * @var SubjectReader
     */
    protected $subjectReader;

    /**
     * Constructor
     *
     * @param ResultInterfaceFactory $resultFactory
     * @param SubjectReader $subjectReader
     */
    public function __construct(ResultInterfaceFactory $resultFactory, SubjectReader $subjectReader)
    {
        parent::__construct($resultFactory);
        $this->subjectReader = $subjectReader;
    }

    /**
     * validate response object from api
     *
     * @param array $subjectValidate
     * @return void
     */
    public function validate(array $subjectValidate)
    {
        /** @var Successful|Error $response */
        $response = $this->subjectReader->readResponseObject($subjectValidate);
    
        $isValid = true;
        $errorMessages = [];
        
        foreach ($this->getResValidators() as $validator) {
            $validationResult = $validator($response);

            if (!$validationResult[0]) {
                $isValid = $validationResult[0];
                $errorMessages = $this->mergeData($errorMessages, $validationResult[1]);
            }
        }

        return $this->createResult($isValid, $errorMessages);
    }

    public function mergeData($errorMessages, $validationResult)
    {
        return array_merge($errorMessages, $validationResult);
    }

    /**
     * @return array
     */
    protected function getResValidators()
    {
        return [
            function ($response) {
                return [
                    !isset($response['error']),
                    [__(isset($response['error'])?$response['error']:'there is some error in request')]
                ];
            }
        ];
    }
}
