<?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\BlazegraphResolver\Filter\Conditional;

use Datatourisme\Api\Resolver\SparqlResolver\Collection\IntersectCollection;
use Datatourisme\Api\Resolver\SparqlResolver\Filter\ConditionalFilterInterface;
use Datatourisme\Api\Resolver\SparqlResolver\Utils\SparqlUtils;
use Datatourisme\Api\Schema\Field\AbstractField;

class GeoBounding implements ConditionalFilterInterface
{
    private $geoProperty;

    public function getName()
    {
        return '_geo_bounding';
    }

    public function generate($subject, AbstractField $fieldDef, $value)
    {
        $service = new IntersectCollection();
        $service->add($subject.' <http://www.bigdata.com/rdf/geospatial#search> "inRectangle"');
        $service->add($subject.' <http://www.bigdata.com/rdf/geospatial#predicate> <'.SparqlUtils::expandUri($this->geoProperty).'>');
        $service->add($subject.' <http://www.bigdata.com/rdf/geospatial#searchDatatype> <http://www.bigdata.com/rdf/geospatial/literals/v1#lat-lon>');
        $service->add($subject.' <http://www.bigdata.com/rdf/geospatial#spatialRectangleSouthWest> "'.$value['sw_lat'].'#'.$value['sw_lng'].'"');
        $service->add($subject.' <http://www.bigdata.com/rdf/geospatial#spatialRectangleNorthEast> "'.$value['ne_lat'].'#'.$value['ne_lng'].'"');

        $sparql = new IntersectCollection();
        $sparql->add('SERVICE <http://www.bigdata.com/rdf/geospatial#search> '.$service);
        $sparql->add('<http://www.bigdata.com/queryHints#SubQuery> <http://www.bigdata.com/queryHints#optimizer> "Static"');

        return $sparql;
    }

    /**
     * @param mixed $geoProperty
     *
     * @return $this
     */
    public function setGeoProperty($geoProperty)
    {
        $this->geoProperty = $geoProperty;

        return $this;
    }
}
