<?php

namespace FiloBlu\Refilo\Model\Wysiwyg\Images;


use Magento\Framework\Exception\LocalizedException;
use Magento\Cms\Model\Wysiwyg\Images\Storage as MagentoImageStorage;

/**
 * Class Storage
 * @package FiloBlu\Refilo\Model\Wysiwyg\Images
 */
class Storage extends MagentoImageStorage
{
    /**
     * @param string $targetPath
     * @param null $type
     * @return array|bool
     * @throws LocalizedException
     */
    public function uploadFile($targetPath, $type = null)
    {

        /** @var \Magento\MediaStorage\Model\File\Uploader $uploader */
        $uploader = $this->_uploaderFactory->create(['fileId' => 'image']);
        $allowed = $this->getAllowedExtensions($type);
        if ($allowed) {
            $uploader->setAllowedExtensions($allowed);
        }
        $uploader->setAllowRenameFiles(true);
        $uploader->setFilesDispersion(false);
        $result = $uploader->save($targetPath);

        if (!$result) {
            throw new LocalizedException(__('We can\'t upload the file right now.'));
        }

        if (strtolower($uploader->getFileExtension()) !== 'pdf') {
            // create thumbnail
            $this->resizeFile($targetPath . '/' . $uploader->getUploadedFileName(), true);
        }

        $result['cookie'] = [
            'name' => $this->getSession()->getName(),
            'value' => $this->getSession()->getSessionId(),
            'lifetime' => $this->getSession()->getCookieLifetime(),
            'path' => $this->getSession()->getCookiePath(),
            'domain' => $this->getSession()->getCookieDomain(),
        ];

        return $result;
    }
}
