<?php

namespace Snaju\Inception\Api\Requests\Types;

use Doctrine\Common\Annotations\AnnotationReader;
use Snaju\Inception\Annotation\OVERRIDE;
use Snaju\Inception\Api\ApiAuthResponse;
use Snaju\Inception\Api\ApiInterface;
use Snaju\Inception\Api\ApiUtility;
use Snaju\Inception\Api\Requests\ApiRequest;
use Snaju\Inception\Api\Returns\ApiReturn;
use Snaju\Inception\Api\Returns\Type\ApiError;
use Snaju\Inception\Api\Returns\Type\ApiSuccess;
use Snaju\Inception\Http\Request\Validators\Validator;
use Snaju\Inception\Http\Request\WebRequest;
use Snaju\Inception\ORM\DataModel;

class PatchRequest extends ApiRequest
{


    /**
     * GetRequest constructor.
     */
    public function __construct()
    {
        $this->method = "PATCH";
    }

    protected function process(WebRequest $request): ApiReturn
    {

        $reader = new AnnotationReader();

        $v = new Validator([
            "id" => "required"
        ]);

        if ($v->hasErrors()) {
            return new ApiError($v->getErrorString());
        }

        $d = $request->getAll();
        if (isset($d['id'])) {

            $params = ApiUtility::getParams($this->modelName, "w");

            $obj = $this->modelName::get($d['id']);
            if ($obj instanceof DataModel && $obj instanceof ApiInterface) {

                $method = new \ReflectionMethod($this->modelName, "api_patch");

                if ($reader->getMethodAnnotation($method, OVERRIDE::class) instanceof OVERRIDE) {
                    return $obj->api_patch($request);
                } else {

//                    /*
//                     * Default Logic
//                     * */
//                    $r = $obj->toArray()->permit($params)->get();

                    foreach ($params as $param) {
                        if (isset($d[$param])) {
                            $obj->setVal($param, $d[$param]);
                        }
                    }

                    $obj->save();

                    return new ApiSuccess($obj->toArray()->permit(ApiUtility::getParams($this->modelName, "r")));
                }
            } else {
                return new ApiError("Invalid Model of " . $this->modelName);
            }
        }

        return new ApiError("Fatal Error");
    }
}