<?php

namespace App\Controller\File;

use App\Entity\File;
use App\Integrations\Shutterstock\Client;
use App\Integrations\Shutterstock\Requests\PostImagesLicenseRequest;
use App\Service\File\Namer\NamerInterface;
use App\Service\FileService;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;
use League\Flysystem\FileExistsException;
use League\Flysystem\Filesystem;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ShutterstockController extends FOSRestController
{
    private $client;
    /**
     * @var FileService
     */
    private $service;
    /**
     * @var Filesystem
     */
    private $filesystem;
    /**
     * @var NamerInterface
     */
    private $namer;

    public function __construct(Client $client, FileService $service, Filesystem $filesystem, NamerInterface $namer)
    {
        $this->client = $client;
        $this->service = $service;
        $this->filesystem = $filesystem;
        $this->namer = $namer;
    }

    /**
     * Retrieves a collection of  resource.
     *
     * @Rest\Post("/file/shutterstock")
     *
     * @param Request $request
     *
     * @return View
     *
     * @throws \League\Flysystem\FileNotFoundException
     */
    public function postFiles(Request $request): View
    {
        $images = [];
        $files = $request->request->get('files');
        foreach ($files as $image) {
            $images[] = [
                'subscription_id' => 's33105787',
                'image_id' => (string) $image,
                'size' => 'medium',
                'format' => 'jpg',
            ];
        }

        $request = (new PostImagesLicenseRequest())->setImages($images);
        $response = $this->client->execute($request);

        $files = [];
        foreach ($response->getBody()['data'] as $file) {
            $name = 'shutterstock_'.$file['image_id'].'.jpg';
            $year = date('Y', time());
            $month = date('m', time());

            $path = $year.'/'.$month.'/'.$name;

            try {
                $stream = fopen($file['download']['url'], 'r');
                $this->filesystem->putStream($path, $stream);
                fclose($stream);
                if (!$file = $this->service->getByTitle($name)) {
                    $fileEntity = (new File())
                        ->setTitle($name)
                        ->setFilename($name)
                        ->setPath($year.'/'.$month.'/')
                        ->setMimetype($this->filesystem->getMimetype($path))
                        ->setSize($this->filesystem->getSize($path));

                    $file = $this->service->save($fileEntity);
                }
                $files[] = $file;
            } catch (FileExistsException $e) {
                return View::create($e->getMessage(), Response::HTTP_BAD_REQUEST);
            }
        }

        return View::create($files, Response::HTTP_OK);
    }
}
