<?php

class PestNova extends Pest
{
    public $token = null;

    public function processBody($body)
    {
        return json_decode($body, true);
    }

    protected function prepRequest($opts, $url)
    {
        $opts[CURLOPT_HTTPHEADER][] = 'Accept: application/vnd.cfengine.nova-v1+json';
        $opts[CURLOPT_HTTPHEADER][] = 'Content-Type: application/json';
        if ($this->token) {
            $opts[CURLOPT_HTTPHEADER][] = 'Authorization: Bearer ' . $this->token;
        }

        return parent::prepRequest($opts, $url);
    }

    // $auth can be 'basic' or 'digest'
    // override here so it resets the Oauth auth token
    public function setupAuth($user, $pass, $auth = 'basic')
    {
        $this->curl_opts[CURLOPT_HTTPAUTH] = constant('CURLAUTH_'.strtoupper($auth));
        $this->curl_opts[CURLOPT_USERPWD] = $user . ":" . $pass;
        $this->token = null;
    }


    public function processError($body)
    {
        if ($this->lastStatus() === 0) {
            return "Error encountered from API server: $body";
        }
        return $body;
    }

    public function setupOauthAuth($token = '')
    {
        if ($token) {
            $this->token = $token;
        }
    }
}
