<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace FiloBlu\Refilo\Controller\Adminhtml\ContentType\Video;

use Exception;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\File\UploaderFactory;
use Magento\Framework\Filesystem\DirectoryList;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;

/**
 * Class Upload
 */
class Upload extends Action implements HttpPostActionInterface
{
    const UPLOAD_DIR = 'video';

    const ADMIN_RESOURCE = 'Magento_Backend::content';

    /**
     * @var DirectoryList
     */
    private $directoryList;

    /**
     * @var JsonFactory
     */
    private $resultJsonFactory;

    /**
     * @var UploaderFactory
     */
    private $uploaderFactory;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * Constructor
     *
     * @param Context $context
     * @param JsonFactory $resultJsonFactory
     * @param StoreManagerInterface $storeManager
     * @param UploaderFactory $uploaderFactory
     * @param DirectoryList $directoryList
     */
    public function __construct(
        Context                                          $context,
        JsonFactory $resultJsonFactory,
        StoreManagerInterface       $storeManager,
        UploaderFactory          $uploaderFactory,
        DirectoryList                                    $directoryList
    )
    {
        parent::__construct($context);
        $this->resultJsonFactory = $resultJsonFactory;
        $this->storeManager = $storeManager;
        $this->uploaderFactory = $uploaderFactory;
        $this->directoryList = $directoryList;
    }

    /**
     * Allow users to upload images to the folder structure
     *
     * @return ResultInterface
     */
    public function execute()
    {
        $fieldName = $this->getRequest()->getParam('param_name');
        $fileUploader = $this->uploaderFactory->create(['fileId' => $fieldName]);

        // Set our parameters
        $fileUploader->setFilesDispersion(false);
        $fileUploader->setAllowRenameFiles(true);
        $fileUploader->setAllowedExtensions(['mp4','webm']);
        $fileUploader->setAllowCreateFolders(true);

        try {

            $result = $fileUploader->save($this->getUploadDir());
            $baseUrl = $this->storeManager->getStore()->getBaseUrl(UrlInterface::URL_TYPE_MEDIA);
            $result['id'] = strtr(base64_encode($result['file']), '+/=', ':_-');
            $result['url'] = $baseUrl . $this->getFilePath(self::UPLOAD_DIR, $result['file']);
        } catch (Exception $e) {
            $result = [
                'error'     => $e->getMessage(),
                'errorcode' => $e->getCode()
            ];
        }
        return $this->resultJsonFactory->create()->setData($result);
    }

    /**
     * Return the upload directory
     *
     * @return string
     * @throws FileSystemException
     */
    private function getUploadDir()
    {
        return $this->directoryList->getPath('media') . DIRECTORY_SEPARATOR . self::UPLOAD_DIR;
    }

    /**
     * Retrieve path
     *
     * @param string $path
     * @param string $videoName
     * @return string
     */
    private function getFilePath($path, $videoName)
    {
        return rtrim($path, '/') . '/' . ltrim($videoName, '/');
    }
}
