<?php

namespace Comitium5\DesignerBundle\Normalizer\Api\Asset;

use Comitium5\ApiClientBundle\Client\Services\AssetApiService;
use Comitium5\ApiClientBundle\ValueObject\IdentifiedValue;
use Comitium5\DesignerBundle\Builder\Api\ClientFromLocaleBuilder;
use Comitium5\DesignerBundle\Normalizer\Api\ApiNormalizerInterface;
use Comitium5\DesignerBundle\Provider\Locale\LocaleProvider;

/**
 * Class AssetTitlesNormalizer
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Normalizer\Api\Asset
 */
class AssetTitlesNormalizer implements ApiNormalizerInterface
{
    /**
     * @var ClientFromLocaleBuilder
     */
    protected $clientBuilder;

    /**
     * @var LocaleProvider
     */
    protected $localeProvider;

    /**
     * AssetTitlesNormalizer constructor.
     *
     * @param ClientFromLocaleBuilder $clientBuilder
     * @param LocaleProvider $localeProvider
     */
    public function __construct(ClientFromLocaleBuilder $clientBuilder, LocaleProvider $localeProvider)
    {
        $this->clientBuilder  = $clientBuilder;
        $this->localeProvider = $localeProvider;
    }

    /**
     * @param array $entity
     *
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function normalize(array $entity): array
    {
        $clientBuilder = $this->clientBuilder;

        $locales = $this
            ->localeProvider
            ->getLocales();

        $defaultLocale = $this
            ->localeProvider
            ->getDefaultLocale()
            ->getCode();

        $titles = [];

        foreach ($locales as $locale) {
            if ($locale->getCode() === $defaultLocale) {
                $titles[$defaultLocale] = $entity["title"];

                continue;
            }

            $client = $clientBuilder($locale->getCode());

            $assetApiService = new AssetApiService($client);

            $assetResult = $assetApiService->find(new IdentifiedValue($entity["id"]));

            $titles[$locale->getCode()] = !empty($assetResult["title"]) ? $assetResult["title"] : "";
        }

        $entity["titles"] = $titles;

        $clientBuilder($defaultLocale);

        return $entity;
    }
}
