<?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 ListRequest extends ApiRequest
{


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

    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_list");

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

                $q = Criteria::create();

                if (isset($d['q'])) {
                    ApiUtility::criteriaFromQueryString($q, $d['q']);
                }

                if (isset($d['order'])) {
                    $orderings = [];
                    foreach (explode(":", $d['order']) as $set) {
                        $p = explode(",", $set);
                        $f = $p[0];
                        $d = $p[1];

                        $orderings[$f] = strtoupper($d);
                    }

                    $q->orderBy($orderings);
                }

                if (isset($d['start'])) {
                    $q->setFirstResult($d['start']);
                }

                if (isset($d['limit'])) {
                    $q->setMaxResults($d['limit']);
                }

                $results = $this->modelName::find($q);

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

                return new ApiList(DataModelArray::build($results, $params));
            }
        }

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