<?php
/*
 * NeutrinoAPI
 *
 * This file was automatically generated for NeutrinoAPI by APIMATIC v2.0 ( https://apimatic.io ).
 */

namespace NeutrinoAPILib\Controllers;

use NeutrinoAPILib\Http\HttpCallBack;
use NeutrinoAPILib\Http\HttpContext;
use NeutrinoAPILib\Http\HttpResponse;
use NeutrinoAPILib\APIException;
use NeutrinoAPILib\Exceptions;
use \apimatic\jsonmapper\JsonMapper;
use Unirest\Request;

/**
* Base controller
*/
class BaseController
{
    /**
     * User-agent to be sent with API calls
     * @var string
     */
    const USER_AGENT = 'APIMATIC 2.0';

    /**
     * HttpCallBack instance associated with this controller
     * @var HttpCallBack
     */
    private $httpCallBack = null;

     /**
     * Constructor that sets the timeout of requests
     */
    protected function __construct()
    {
        Request::timeout(90);
    }

    /**
     * Set HttpCallBack for this controller
     * @param HttpCallBack $httpCallBack Http Callbacks called before/after each API call
     */
    public function setHttpCallBack(HttpCallBack $httpCallBack)
    {
        $this->httpCallBack = $httpCallBack;
    }

    /**
     * Get HttpCallBack for this controller
     * @return HttpCallBack The HttpCallBack object set for this controller
     */
    public function getHttpCallBack()
    {
        return $this->httpCallBack;
    }

    /**
     * Get a new JsonMapper instance for mapping objects
     * @return \apimatic\jsonmapper\JsonMapper JsonMapper instance
     */
    protected function getJsonMapper()
    {
        $mapper = new JsonMapper();
        return $mapper;
    }

    protected function validateResponse(HttpResponse $response, HttpContext $_httpContext)
    {
        if ($response->getStatusCode() == 400) {
            throw new Exceptions\APIErrorException(
                'Your API request has been rejected. Check error code for details',
                $_httpContext
            );
        }
        if ($response->getStatusCode() == 403) {
            throw new Exceptions\APIErrorException('You have failed to authenticate', $_httpContext);
        }
        if ($response->getStatusCode() == 500) {
            throw new Exceptions\APIErrorException(
                'We messed up, sorry! Your request has caused a fatal exception',
                $_httpContext
            );
        }
        if (($response->getStatusCode() < 200) || ($response->getStatusCode() > 208)) { //[200,208] = HTTP OK
            throw new Exceptions\APIErrorException('We messed up, sorry! Your request has caused an error', $_httpContext);
        }
    }
}
