<?php

namespace CorpusParole\Http\Controllers\Proxy;

use Guzzle;

use Illuminate\Http\Request;

use CorpusParole\Http\Requests;
use CorpusParole\Http\Controllers\Controller;


class BnfController extends Controller
{

    const HEADERS_FORWARDED = [ "host", "user-agent", "accept", "accept-language", "accept-encoding", "connection" ];

    private function proxyQuery($req, $url) {

        $headers = [];
        foreach (BnfController::HEADERS_FORWARDED as $h) {
            $headerValue = $req->header($h);
            if($headerValue) {
                $headers[$h] = $headerValue;
            }
        }

        $complResp = Guzzle::get($url, ['query' => $req->all(), 'headers' => $headers]);

        $resp = response((string)$complResp->getBody(), $complResp->getStatusCode());
        foreach ($complResp->getHeaders() as $name => $values) {
            if($name != 'Transfer-Encoding') {
                $resp->header($name, $values);
            }
        }

        return $resp;

    }

    // proxy Auto completion query for bnf
    public function proxyAutoCompletion(Request $req) {
        return $this->proxyQuery($req, config('corpusparole.bnf_completion_url'));
    }

    // proxy sparql query for bnf
    public function proxySparql(Request $req) {

        return $this->proxyQuery($req, config('corpusparole.bnf_query_url'));

    }

}
