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

use Datatourisme\Api\Resolver\SparqlResolver\Collection\FlatCollection;
use Datatourisme\Api\Resolver\SparqlResolver\Filter\ConditionalFilterInterface;
use Datatourisme\Api\Resolver\SparqlResolver\Sparql\Functions\Filter;
use Datatourisme\Api\Resolver\SparqlResolver\Sparql\Triplet;
use Datatourisme\Api\Resolver\SparqlResolver\Utils\SparqlUtils;
use Datatourisme\Api\Schema\Field\AbstractField;

class GeoBounding implements ConditionalFilterInterface
{
    private $latitudeProperty;
    private $longitudeProperty;

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

    public function generate($subject, AbstractField $fieldDef, $value)
    {
        $set = new FlatCollection();

        $latId = SparqlUtils::uniqVariable($subject, $this->latitudeProperty);
        $lngId = SparqlUtils::uniqVariable($subject, $this->longitudeProperty);

        $set->add(new Triplet($subject, '<'.$this->latitudeProperty.'>', $latId));
        $set->add(new Triplet($subject, '<'.$this->longitudeProperty.'>', $lngId));

        $set->add(new Filter($latId.' >= '.SparqlUtils::formatLiteralValue($value['sw_lat'], 'http://www.w3.org/2001/XMLSchema#float')));
        $set->add(new Filter($latId.' <= '.SparqlUtils::formatLiteralValue($value['ne_lat'], 'http://www.w3.org/2001/XMLSchema#float')));
        $set->add(new Filter($lngId.' >= '.SparqlUtils::formatLiteralValue($value['sw_lng'], 'http://www.w3.org/2001/XMLSchema#float')));
        $set->add(new Filter($lngId.' <= '.SparqlUtils::formatLiteralValue($value['ne_lng'], 'http://www.w3.org/2001/XMLSchema#float')));

        return $set;
    }

    /**
     * @param $latitudeProperty
     *
     * @return $this
     */
    public function setLatitudeProperty($latitudeProperty)
    {
        $this->latitudeProperty = $latitudeProperty;

        return $this;
    }

    /**
     * @param $longitudeProperty
     *
     * @return $this
     */
    public function SetLongitudeProperty($longitudeProperty)
    {
        $this->longitudeProperty = $longitudeProperty;

        return $this;
    }
}
