<?php
namespace Autogedal\Helper\Controller;

use Mageplaza\ProductAttachments\Controller\File\Download;
use Exception;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\Http\FileFactory;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\Result\Raw;
use Magento\Framework\Controller\Result\RawFactory;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\ReadFactory;
use Magento\Store\Model\StoreManagerInterface;
use Mageplaza\ProductAttachments\Helper\Data;
use Mageplaza\ProductAttachments\Helper\File as FileHelper;
use Mageplaza\ProductAttachments\Model\File;
use Mageplaza\ProductAttachments\Model\FileFactory as MpFileFactory;
use Mageplaza\ProductAttachments\Model\Log;
use Mageplaza\ProductAttachments\Model\LogFactory as MpLogFactory;

class ProductAttachmentsOverride extends Download
{
    public function execute()
    {
        $customerId = $this->_customerSession->isLoggedIn() ? $this->_customerSession->getCustomer()->getId() : 0;
        $fileId = $this->getRequest()->getParam('id');
        $productId = $this->getRequest()->getParam('product_id');

        /** @var File $file */
        $file = $this->_mpFileFactory->create()->load($fileId);
        if ($file->getCustomerLogin() && !$this->_customerSession->isLoggedIn()) {
            return $this->_redirect('noroute');
        }
        if ($file->getIsBuyer() && !$this->_helperData->isPurchased($file->getIsBuyer(), $productId)) {
            return $this->_redirect('noroute');
        }

        $fileAbsolutePath = FileHelper::TEMPLATE_MEDIA_PATH . '/'
            . FileHelper::TEMPLATE_MEDIA_TYPE_FILE . '/' . $file->getFilePath();
        $mediaPath = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
        $directoryRead = $this->_readFactory->create($mediaPath);

        //We don't have the size for old files so we need to get it
        //Lately we used 500kb as size to look better on FE. So we need to get the size in this case
        $fileSize = $file->getSize();
        if (file_exists($mediaPath . $fileAbsolutePath) && $fileSize == 500000) {
            $fileSize = filesize($mediaPath . $fileAbsolutePath);
        }
        $this->_fileFactory->create(
            $file->getName(),
            null,
            DirectoryList::PUB,
            'application/octet-stream',
            $fileSize
        );

        /** @var Log $file */
        $log = $this->_mpLogFactory->create();
        $logData = [
            'file_id'        => $fileId,
            'customer_id'    => $customerId,
            'product_id'     => $productId,
            'file_action'    => $file->getFileAction(),
            'store_id'       => $this->_storeManager->getStore()->getId(),
            'customer_group' => $this->_customerSession->getCustomer()->getGroupId()
        ];
        $log->addData($logData)->save();

        /** @var Raw $resultRaw */
        $resultRaw = $this->resultRawFactory->create();
        $resultRaw->setContents($directoryRead->readFile($fileAbsolutePath));

        return $resultRaw;
    }
}