<?php

namespace idoit\Module\System\Controller;

use Exception;
use GuzzleHttp\Psr7\MimeType;
use isys_application;
use SplFileInfo;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;

/**
 * System relevant download controller.
 *
 * @package   Modules
 * @copyright synetics GmbH
 * @license   http://www.i-doit.com/license
 */
class DownloadController
{
    /**
     * @param Request $request
     * @param string  $type
     * @param string  $identifier
     *
     * @return Response
     * @throws Exception
     */
    public function process(Request $request, string $type, string $identifier): Response
    {
        $downloadService = isys_application::instance()->container->get('download');

        if (!$downloadService->hasDownloadType($type)) {
            throw new Exception("The given download type '{$type}' does not exist!");
        }

        $filePath = $downloadService->getDownloadType($type)->getCallback()($identifier);

        if (!file_exists($filePath)) {
            throw new Exception('The given file does not exist!');
        }

        $file = new SplFileInfo($filePath);

        return new BinaryFileResponse(
            $file,
            200,
            ['Content-Type' => MimeType::fromExtension($file->getExtension()) ?? 'application/octet-stream'],
            true,
            ResponseHeaderBag::DISPOSITION_ATTACHMENT
        );
    }
}
