<?php

declare(strict_types=1);

namespace App\Controller\Content;

use App\Service\Content\ContentFileExporter;
use App\Service\Content\PlacementService;
use App\Service\ContentService;
use Doctrine\ORM\EntityNotFoundException;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\KernelInterface;
use Webmozart\Assert\Assert;

class DownloadController extends FOSRestController
{
    private $service;
    /**
     * @var ContentFileExporter
     */
    private $contentFileExporter;
    /**
     * @var ContentService
     */
    private $contentService;

    public function __construct(PlacementService $service, ContentService $contentService, ContentFileExporter $contentFileExporter)
    {
        $this->service = $service;
        $this->contentFileExporter = $contentFileExporter;
        $this->contentService = $contentService;
    }

    /**
     * Retrieves a collection of Placement resource.
     *
     * @Rest\Get("/content/{content}/download")
     *
     * @param Request $request
     *
     * @return Response|View
     */
    public function getAction(int $content, Request $request, KernelInterface $kernel)
    {
        try {
            $content = $this->contentService->getContent($content);
        } catch (EntityNotFoundException $e) {
            return View::create(['code' => Response::HTTP_NOT_FOUND, 'message' => $e->getMessage()], Response::HTTP_NOT_FOUND);
        }

        $type = $request->get('type');

        try {
            Assert::oneOf($type, ['pdf', 'docx']);
        } catch (\Exception $e) {
            return View::create(['code' => Response::HTTP_BAD_REQUEST, 'message' => $e->getMessage()], Response::HTTP_BAD_REQUEST);
        }

        $file = $this->contentFileExporter->export($content, strtoupper($type));
        $path = sprintf('%s/public/uploads/%s/%s', $kernel->getProjectDir(), $file->getPath(), $file->getFilename());

        $file = new File($path);

        return $this->file($file, $file->getFilename());
    }
}
