<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Jure
 * Date: 12.3.14
 * Time: 10:54
 * To change this template use File | Settings | File Templates.
 */

class NFieldHttpClient implements INfieldHttpClient
{
     private $httpClient = null;
     public function __construct($uri){
            $this->httpClient = new HttpClient($uri);
     }
    public function send($request)
    {
        // TODO: Implement send() method.
    }

    public function post($requestUri, $content)
    {
        $header = $this->checkAndHandleAuthenticationToken($this->httpClient);


        return $this->httpClient->post($requestUri,$this->prepareDataToClient($content),$header);
    }

    public function get($requestUri)
    {
       $header = $this->checkAndHandleAuthenticationToken($this->httpClient);

       return $this->httpClient->get($requestUri,$data = array(),$header);
    }


    public function delete($requestUri)
    {
        $header = $this->checkAndHandleAuthenticationToken($this->httpClient);
        return $this->httpClient->delete($requestUri,$header);

    }

    public function patch($requestUri, $content)
    {
        $header = $this->checkAndHandleAuthenticationToken($this->httpClient);
        return $this->httpClient->patch($requestUri,$this->prepareDataToClient($content),$header);
    }

    public function put($requestUri, $content)
    {
        $header = $this->checkAndHandleAuthenticationToken($this->httpClient);
        return $this->httpClient->put($requestUri,$this->prepareDataToClient($content),$header);
    }

    private function checkAndHandleAuthenticationToken($httpClient)
    {
        $login = array(
            'Domain'=>'RM Plus',
            'Username'=>'da',
           'Password'=>'Pa$$w0rd1234'
        );
        $token = $httpClient->post('/SignIn',$login);

        $token = $this->managedToken($token);
        $header = array(
            'Authorization'=>'Basic '.$token[1],
            'Content-Type' => 'application/json'
        );
        return $header;
    }

    private function prepareDataToClient($object){
        $object = $this->convertObjectToArrayAndTrimNullValues($object);
        return $this->encodeArrayToJson($object);
    }

    private function encodeArrayToJson($array){
        return json_encode($array);
    }
    private function convertObjectToArrayAndTrimNullValues($object){
        return array_filter(get_object_vars($object), 'strlen');
    }

    private function managedToken($token)
    {
        $token = explode(':', $token);
        $token[1] = substr($token[1], 0, 98);
        $remove[] = "'";
        $remove[] = '"';
        $remove[] = "-"; // just as another example
        $token[1] = str_replace($remove, "", $token[1]);
        return $token;
    }

}
