<?php

namespace Comitium5\DesignerBundle\Factory;

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

/**
 * Class CollectionNormalizerFactory
 *
 * @author David Carrascosa <david@bab-soft.com>
 * @package Comitium5\DesignerBundle\Factory
 */
class CollectionNormalizerFactory implements CollectionNormalizerFactoryInterface
{
    /**
     * @var ApiServiceInterface
     */
    protected $apiService;

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

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

    /**
     * @param ParametersValue $parametersValue
     *
     * @return array
     * @throws \Exception
     */
    public function create(ParametersValue $parametersValue): array
    {
        $response = $this
            ->apiService
            ->findBy($parametersValue);

        if (empty($response['results'])) {
            throw new \Exception(
                sprintf(
                    "Can not normalize %s collection",
                    get_class($this->apiService)
                )
            );
        }

        foreach ($response['results'] as &$entity) {
            $entity = $this
                ->normalizerFactory
                ->create($entity);
        }

        return $response['results'];
    }
}