<?php

namespace Comitium5\DesignerBundle\UseCase\Asset;

use Comitium5\ApiClientBundle\Client\Services\AssetApiService;
use Comitium5\ApiClientBundle\ValueObject\ParametersValue;
use Comitium5\DesignerBundle\Factory\Pagination\KnpPaginationFactory;
use Comitium5\DesignerBundle\Model\Interfaces\Pagination\PaginationInterface;
use Comitium5\DesignerBundle\Model\Interfaces\Pagination\PaginatorInterface;
use Comitium5\DesignerBundle\ValueObjects\Asset\SearchAssetObject;

/**
 * Class SearchAssetUseCase
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\UseCase\Asset
 */
class SearchAssetUseCase
{
    /**
     * @param AssetApiService $assetApiService
     * @param PaginatorInterface $paginator
     * @param SearchAssetObject $searchAssetObject
     * @param array $normalizers
     *
     * @return PaginationInterface
     * @throws \Exception
     */
    public function __invoke(
        AssetApiService $assetApiService,
        PaginatorInterface $paginator,
        SearchAssetObject $searchAssetObject,
        array $normalizers = []
    ): PaginationInterface {
        $response = $assetApiService->findBy(new ParametersValue([
            "title"   => $searchAssetObject->getSearchText(),
            "type"    => $searchAssetObject->getType(),
            "limit"   => $searchAssetObject->getQuantity(),
            "private" => 0,
            "order"   => "id desc",
            "page"    => $searchAssetObject->getPage(),
            "parent"  => 0,
        ]));

        foreach ($response["results"] as &$asset) {
            foreach ($normalizers as $normalizer) {
                $asset = $normalizer->normalize($asset);
            }
        }

        return KnpPaginationFactory::createForApi(
            $paginator,
            $response
        );
    }
}
