<?php

namespace Snaju\Inception\Api\Requests\Types;

use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Collections\Criteria;
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\ApiList;
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;
use Snaju\Inception\ORM\DataModelArray;

class PostRequest extends ApiRequest
{


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

    protected function process(WebRequest $request): ApiReturn
    {

        $reader = new AnnotationReader();
        $obj = new $this->modelName();

        if ($obj instanceof DataModel && $obj instanceof ApiInterface) {
            $d = $request->getAll();

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

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


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

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

                $obj->save();

                $paramsRead = ApiUtility::getParams($this->modelName, "r");

                return new ApiSuccess($obj->toArray()->permit($paramsRead)->get());
            }
        }

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