<?php

namespace Comitium5\DesignerBundle\Tests\UseCase\Asset;

use Comitium5\ApiClientBundle\Client\Services\AssetApiService;
use Comitium5\DesignerBundle\Tests\AbstractTestCase;
use Comitium5\DesignerBundle\UseCase\Asset\UploadAssetUseCase;
use Comitium5\DesignerBundle\ValueObjects\Asset\UploadAssetObject;

/**
 * Class UploadAssetUseCaseTest
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Tests\UseCase\Asset
 */
class UploadAssetUseCaseTest extends AbstractTestCase
{
    /**
     * @throws \ErrorException
     */
    public function testUpload()
    {
        $tmp = tmpfile();
        $title = "foo";

        $useCase = new UploadAssetUseCase($this->assetApiService($title));

        $assetObject = $useCase(
            $title,
            stream_get_meta_data($tmp)['uri'],
            "image"
        );

        $this->assertInstanceOf(UploadAssetObject::class, $assetObject);
        $this->assertEquals(1, $assetObject->getId());
        $this->assertEquals($title, $assetObject->getTitle());
        $this->assertEquals("/path/to", $assetObject->getDirectoryPath());
        $this->assertEquals("/path/to/foo.jpg", $assetObject->getPath());
    }

    /**
     * @throws \ErrorException
     */
    public function testUploadOnCreationFailure()
    {
        $tmp = tmpfile();
        $title = "foo";

        $useCase = new UploadAssetUseCase($this->assetApiServiceWithEmptyResult());

        $assetObject = $useCase(
            $title,
            stream_get_meta_data($tmp)['uri'],
            "image"
        );

        $this->assertNull($assetObject);
    }

    /**
     * @param string $title
     *
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function assetApiService(string $title)
    {
        $mock = $this->createMock(AssetApiService::class);

        $mock
            ->method("post")
            ->willReturn([
                "id" => 1,
                "title" => $title,
                "path" => "/path/to/foo.jpg"
            ]);

        return $mock;
    }

    /**
     * @return \PHPUnit_Framework_MockObject_MockObject
     */
    private function assetApiServiceWithEmptyResult()
    {
        $mock = $this->createMock(AssetApiService::class);

        $mock
            ->method("post")
            ->willReturn([]);

        return $mock;
    }
}
