<?php
// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: RDFTransformerSpreadsheet.php,v 1.1.2.3 2025/07/01 10:26:56 rtigero Exp $

namespace Pmb\ImportExport\Models\RDFTransformers\RDFTransformerSpreadsheet;

use Pmb\ImportExport\Models\RDFTransformers\RDFTransformerCSV\RDFTransformerCSV;
use Pmb\ImportExport\Models\Chunks\ChunkSpreadsheet\ChunkSpreadsheet;

class RDFTransformerSpreadsheet extends RDFTransformerCSV
{

    public function toTriples($entity)
    {
        $chunk = $this->source->getChunk();
        $parameters = $chunk->getParameters();
        $headerline = $parameters['headerline'] ?? 0;
        $enclosure = $parameters['enclosure'] ?? ChunkSpreadsheet::ENCLOSURE;
        $enclosure_length = strlen($enclosure);
        $separator = $parameters['separator'] ?? ChunkSpreadsheet::SEPARATOR;
        $separator = $enclosure . $separator . $enclosure;
        $tmp_entity = explode("\r\n", $entity);

        if ('' != $enclosure) {
            $tmp_entity[0] = substr($tmp_entity[0], $enclosure_length, -$enclosure_length);
            if (!empty($tmp_entity[1])) {
                $tmp_entity[1] = substr($tmp_entity[1], $enclosure_length, -$enclosure_length);
            }
        }
        if ($headerline) {
            $keys = explode($separator, $tmp_entity[0]);
            $values = explode($separator, $tmp_entity[1]);
            if (count($keys) == count($values)) {
                $entity = array_combine($keys, $values);
            } else {
                $entity = $values;
            }
        } else {
            $entity = explode($separator, $tmp_entity[0]);
        }

        $subject = $this->getPrefix() . 'line_' . $this->entityId;
        $this->addEntity(static::ENTITY_NAME, static::ENTITY_NAME);

        $predicate = 'rdf:type';
        $object = $this->getPrefix() . static::ENTITY_NAME;
        $this->triples[] = $subject . " " . $predicate . " " . $object;

        foreach ($entity as $propertyName => $value) {
            $property = $propertyName;
            if (is_numeric($propertyName)) {
                $property = "col" . $propertyName;
            }
            $this->addProperty($property, $propertyName, array($this->getPrefix() . static::ENTITY_NAME), array(static::LITERAL_TYPE));
            $property = $this->getPrefix() . $property;
            $this->addTriple($subject, $property, $value);
        }
        $this->storeTriples();
    }
}
