<?php

namespace Velis\Api;

use InvalidArgumentException;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class NormalizerFactory
{
    const CONTEXT_LIST = 'ListItem';
    const CONTEXT_SINGLE = '';

    public function createNormalizer($inputDataClass, $apiVersion, $context): NormalizerInterface
    {
        $fqcnArray = explode('\\', $inputDataClass);
        $module = array_shift($fqcnArray);

        $normalizerClassName = sprintf('%s%sNormalizer', array_pop($fqcnArray), $context);
        $normalizerNamespace = sprintf('%s\\Api\\V%s', $module, $apiVersion);

        if (count($fqcnArray)) {
            $normalizerNamespace .= implode('\\', $fqcnArray);
        }

        $normalizerFqcn = sprintf('%s\\%s', $normalizerNamespace, $normalizerClassName);
        if (!class_exists($normalizerFqcn)) {
            throw new InvalidArgumentException(sprintf('Could not find normalizer class for %s class, %s API version, %s context', $inputDataClass, $apiVersion, $context ?: 'single item'));
        }

        return new $normalizerFqcn();
    }
}
