<?php

namespace Comitium5\DesignerBundle\UseCase\Asset;

use Comitium5\ApiClientBundle\Client\Services\AssetApiService;
use Comitium5\ApiClientBundle\Normalizer\RequestParametersNormalizer\GuzzleMultipartParametersNormalizer;
use Comitium5\ApiClientBundle\ValueObject\FileValue;
use Comitium5\DesignerBundle\ValueObjects\Asset\UploadAssetObject;

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

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

    /**
     * @param string $title
     * @param string $filePath
     * @param string $type
     *
     * @return UploadAssetObject|null
     * @throws \ErrorException
     */
    public function __invoke(string $title, string $filePath, string $type): ?UploadAssetObject
    {
        $response = $this
            ->assetApiService
            ->post(new GuzzleMultipartParametersNormalizer([
                "defaultLang[title]" => $title,
                "defaultLang[metaTitle]" => $title,
                "type" => $type,
            ], [
                new FileValue("file", $filePath),
            ]));

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

        $hasDimensions = !empty($response["metadata"]["width"]) && !empty($response["metadata"]["height"]);

        return new UploadAssetObject(
            $response["id"],
            $response["path"],
            $response["title"],
            $hasDimensions ? $response["metadata"]["width"] : null,
            $hasDimensions ? $response["metadata"]["height"] : null
        );
    }
}
