<?php
// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: StepConverter.php,v 1.6.2.3 2025/07/25 13:48:50 rtigero Exp $

namespace Pmb\ImportExport\Models\Steps\StepConverter;

use Pmb\ImportExport\Models\Converters\Converter;
use Pmb\ImportExport\Models\ImportExportParserDirectory;
use Pmb\ImportExport\Models\Steps\Step;

class StepConverter extends Step
{

    protected static $converters;

    protected Converter $converter;

    public function execute($sourceData = array())
    {

        $this->setSourceContextParameters($sourceData);
        $this->instanciateConverter();
        $this->converter->init();
        $this->converter->execute();
        $this->source->setOutFormat($this->converter->getOutFormat());
    }

    public static function getConverters()
    {
        if (!is_null(static::$converters)) {
            return static::$converters;
        }

        static::$converters = [];
        $parser = ImportExportParserDirectory::getInstance();
        $manifests = $parser->getManifests("Pmb/ImportExport/Models/Converters");
        foreach ($manifests as $manifest) {
            static::$converters[] = array(
                'type' => $manifest->type,
                'namespace' => $manifest->namespace,
                'settings' => $manifest->settings,
                'contextParameters' => $manifest->contextSettings,
                'msg' =>  $manifest->namespace::getMessages(),
            );
        }
        return static::$converters;
    }

    public static function getSubConverters($data)
    {
        return $data->converter::getSubConverters();
    }

    protected function instanciateConverter()
    {
        if (! isset($this->stepSettings->converter)) {
            throw new \Exception("No converter defined");
        }
        $converterName = $this->stepSettings->converter;
        $this->converter = new $converterName();
        $this->converter->source = $this->source;
        if (isset($this->stepSettings->rules)) {
            $this->converter->setRules($this->stepSettings->rules);
        }
        if (isset($this->stepSettings->$converterName) && is_a($this->stepSettings->$converterName, "stdClass")) {
            $this->converter->settings = $this->stepSettings->$converterName;
        }
    }
}
