<?php

namespace Comitium5\DesignerBundle\Factory;

use Comitium5\ApiClientBundle\Client\Services\ApiServiceInterface;
use Comitium5\ApiClientBundle\ValueObject\IdentifiedValue;

/**
 * Class NormalizerFactory
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Factory
 */
class NormalizerFactory
{
    /**
     * @var ApiServiceInterface
     */
    protected $apiService;

    /**
     * @var NormalizerFactoryInterface
     */
    private $normalizerFactory;

    /**
     * NormalizerFactory constructor.
     *
     * @param ApiServiceInterface $apiService
     * @param NormalizerFactoryInterface $normalizerFactory
     */
    public function __construct(
        ApiServiceInterface $apiService,
        NormalizerFactoryInterface $normalizerFactory
    ) {
        $this->apiService = $apiService;
        $this->normalizerFactory = $normalizerFactory;
    }

    /**
     * @param IdentifiedValue $identifiedValue
     *
     * @return mixed
     * @throws \Exception
     */
    public function create(IdentifiedValue $identifiedValue)
    {
        $response = $this
            ->apiService
            ->find($identifiedValue);

        if (empty($response)) {
            throw new \Exception(sprintf(
                "Can not normalize %s with id %s",
                get_class($this->apiService),
                $identifiedValue->getId()
            ));
        }

        return $this
            ->normalizerFactory
            ->create($response);
    }
}
