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

use Datatourisme\Api\Schema\Field\AbstractField;
use Datatourisme\Api\Schema\PrefixMap;

class SparqlUtils
{
    /**
     * @var PrefixMap
     */
    public static $prefixMap = null;

    /**
     * @param $uri
     *
     * @return string
     */
    public static function expandUri($uri)
    {
        $pos = strpos($uri, ':');
        if (false === $pos) {
            // handle graphql notation (prefix_property)
            $pos = strpos($uri, '_');
            if (false !== $pos) {
                $uri = substr_replace($uri, ':', $pos, 1);
            } else {
                $uri = ':'.$uri;
            }
        }

        return self::$prefixMap->expandUri($uri);
    }

    /**
     * @param $uri
     *
     * @return string
     */
    public static function shortenUri($uri)
    {
        return self::$prefixMap->shortenUri($uri);
    }

    /**
     * @param $value
     * @param $datatype
     *
     * @return string
     */
    public static function formatLiteralValue($value, $datatype = null)
    {
        $value = '"'.str_replace('"', '\"', $value).'"';
        if ($datatype) {
            $value .= '^^<'.$datatype.'>';
        }

        return $value;
    }

    /**
     * @param $value
     *
     * @return string
     */
    public static function formatFieldValue($value, AbstractField $fieldDef)
    {
        if ('_now_' == $value) {
            return '<http://www.w3.org/2001/XMLSchema#date>(NOW())';
        }

        if (!$fieldDef->isDatatypeProperty()) {
            if (preg_match('/\w+:(\/?\/?)[^\s]+/', $value)) {
                return "<$value>";
            }
        }

        return self::formatLiteralValue($value, $fieldDef->getDatatype());
    }

    /**
     * @param $s
     * @param $p
     * @param $o
     *
     * @return string
     */
    public static function uniqVariable($s, $p = null, $o = null)
    {
        return '?'.substr(md5(serialize(array($s, $p, $o))), 0, 8);
    }
}
