<?php

namespace Comitium5\DesignerBundle\UseCase\Asset;

use Comitium5\ApiClientBundle\Client\Services\AssetApiService;
use Comitium5\ApiClientBundle\Normalizer\RequestParametersNormalizer\GuzzleFormParametersNormalizer;
use Comitium5\ApiClientBundle\Normalizer\RequestParametersNormalizer\GuzzleJsonParametersNormalizer;
use Comitium5\DesignerBundle\ValueObjects\Asset\UploadAssetObject;

/**
 * Class UploadExternalAssetUseCase
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\UseCase\Asset
 */
class UploadExternalAssetUseCase
{
    /**
     * @var AssetApiService
     */
    protected $assetApiService;

    /**
     * UploadAssetUseCase constructor.
     *
     * @param AssetApiService $assetApiService
     */
    public function  __construct(AssetApiService $assetApiService)
    {
        $this->assetApiService = $assetApiService;
    }

    /**
     * @param string $fileUrl
     * @param string $type
     *
     * @return UploadAssetObject|null
     */
    public function __invoke(string $fileUrl, string $type): ?UploadAssetObject
    {
        $response = $this
            ->assetApiService
            ->post(new GuzzleJsonParametersNormalizer([
                "defaultLang" => [
                    "title" => $fileUrl,
                    "metaTitle" => $fileUrl,
                ],
                "type" => $type,
                "file" => $fileUrl,
                "external" => true,
            ]));

        if (empty($response)) {
            return null;
        }

        return new UploadAssetObject(
            $response["id"],
            $response["path"],
            $response["title"]
        );
    }
}
