<?php

namespace Webkul\DamBundle\Controller;

/**
 * @author Aman Srivastava (aman.srivastava462@webkul.com)
 * @copyright 2019 Webkul Soft Pvt. Ltd.
 */
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Doctrine\ORM\EntityManagerInterface;
use Webkul\DamBundle\Entity\AssetMedia;
use Symfony\Component\HttpFoundation\JsonResponse;
use Webkul\DamBundle\Listener\ClassDefinationForCompatibility;

$versionCompatiblility = new ClassDefinationForCompatibility();
$versionCompatiblility->createClassAliases();

class MediaController extends Controller
{
    /**
     * @param string $identifier
     *
     * @throws NotFoundHttpException
     *
     * @return \StreamedFileResponse
     */
    public function downloadAction($identifier)
    {
        $filename = urldecode($identifier);
        if (strpos($filename, '/tmp/pim/file_storage/') !== false) {
            $filename = str_replace('/tmp/pim/file_storage/', '', $filename);
        }
        
        $fileInfoRepository = $this->get('akeneo_file_storage.repository.file_info');
        $fileSystemProvide = $this->get('akeneo_file_storage.file_storage.filesystem_provider');
        $fs = $fileSystemProvide->getFilesystem('catalogStorage');
        if ($fs->has($filename)) {
            $stream = $fs->readStream($filename);
            $headers = [];

            if (null !== $fileInfo = $fileInfoRepository->findOneByIdentifier($filename)) {
                $headers['Content-Disposition'] = sprintf(
                    'attachment; filename="%s"',
                    $fileInfo->getOriginalFilename()
                );
            }
            
            return new \StreamedFileResponse($stream, 200, $headers);
        }

        throw new NotFoundHttpException(
            sprintf('File with key "%s" could not be found.', $filename)
        );
    }
    public function checkAzureAction()
    {
        $responseData['AzureBundle'] = false;
        if (class_exists("Webkul\AzureBlobIntegrationBundle\AzureBlobIntegrationBundle")) {
            $responseData['AzureBundle'] = true;
        }
        return new JsonResponse($responseData);
    }
}
