<?php
/**
 * This file is part of the DATAtourisme project.
 *
 *  @author Conjecto <contact@conjecto.com>
 *
 * For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Datatourisme\Api\Resolver\VirtuosoResolver;

use Datatourisme\Api\Exception\RuntimeException;
use Datatourisme\Api\Resolver\SparqlResolver\SparqlResolver;

class VirtuosoResolver extends SparqlResolver
{
    protected $defaultGraphUri = '';

    /**
     * @param $defaultGraphUri
     */
    public function setDefaultGraphUri($defaultGraphUri)
    {
        $this->defaultGraphUri = $defaultGraphUri;
    }

    /**
     * @param $sparql
     * @param bool $count
     *
     * @return mixed
     *
     * @throws \Exception
     */
    public function execute($sparql, $count = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->endpoint);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'default-graph-uri' => $this->defaultGraphUri, 
            'query' => $sparql
            //todo : add timeout
        ]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain'));
        $result = curl_exec($ch);

        // fix easyrdf on EasyRdf/Format::guessFormat()
        $result = str_replace(">\t", '> ', $result);

        if (false === $result) {
            $code = curl_errno($ch);
            switch ($code) {
                case CURLE_COULDNT_CONNECT:
                    throw new RuntimeException('sparql endpoint unreachable');
            }
            throw new \Exception(curl_error($ch));
        }
        curl_close($ch);

        if ($count) {
            preg_match('/sparql-results#value> \"(\d+)/i', $result, $matches);
            if (isset($matches[1])) {
                return intval($matches[1]);
            }

            return 0;
        }

        return $result;
    }
}
