<?php

namespace App\APIWrapper;

use App\APIWrapper\Server\ServerCalls;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class Wrapper{

    public $methods;
    public $payload = null;
    public $response = null;
    private $method = 'start';
    public $register;

    public function register($registry)
    {
        $cursor = new $registry();
        $this->methods = $cursor->handle();
        $this->payload = $cursor->payload();
        $this->response = $cursor->response();
        $this->register = $registry;
        return $cursor;
    }

    public function call($func, $payload){
        try {
            if ($this->payload->error)
                return $this->payload;

            return call_user_func([ServerCalls::class, $this->method], $payload->merge(array_merge($this->methods, (array) $this->response, array('vendor'=>$this->register, 'addPayload' => $this->payload->request->all()))), $func);
        }catch (ValidationException $e){
            return implode("&",array_map(function($a) {return implode("~",$a);},$e->errors()));
        }
    }

    public function initiate($func){
        return $this->response->resolveResponse($func, $this->call(
            $func,
            new Request(
                $this->payload->getPayload($func)
            )
        ), $this->payload->request);
    }
}