<?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\HdtResolver;

use Datatourisme\Api\Exception\QueryParseException;
use Datatourisme\Api\Resolver\SparqlResolver\SparqlResolver;
use Symfony\Component\Filesystem\Exception\IOException;

class HdtResolver extends SparqlResolver
{
    private $HDTBin;

    public function execute($sparql, $count = false)
    {
        if (!file_exists($this->endpoint)) {
            throw new IOException('File '.$this->endpoint.' not found');
        }
        if (!isset($this->HDTBin)) {
            $this->HDTBin = __DIR__.'/../../../java/hdt-resolver.jar';
            if (!file_exists($this->HDTBin)) {
                throw new IOException('File '.$this->HDTBin.' not found');
            }
        }
        $sparql = str_replace("\n", ' ', $sparql);
        $result = shell_exec('java -jar '.$this->HDTBin.' '.$this->endpoint.' "'.addslashes($sparql).'"');

        if ('Parse error' == substr($result, 0, 11)) {
            throw new QueryParseException($result);
        }
        if ($count) {
            preg_match('/c[^\d]+(\d+)/', $result, $matches);
            if (isset($matches[1])) {
                return intval($matches[1]);
            }

            return 0;
        }

        return $result;
    }

    /**
     * @param mixed $HDTFile
     */
    public function setHDTBin($HDTFile)
    {
        $this->HDTBin = $HDTFile;
    }
}
