<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Images;

use Exception;
use FiloBlu\Storelocator\Model\Images;
use FiloBlu\Storelocator\Model\ImagesFactory;
use FiloBlu\Storelocator\Model\Stores\Image;
use Magento\Backend\App\Action;
use Magento\Backend\Model\View\Result\Redirect;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\File\Uploader;
use Magento\MediaStorage\Model\File\UploaderFactory;
use RuntimeException;

/**
 *
 */
class Save extends Action
{
    /**
     * @var \Magento\MediaStorage\Model\File\UploaderFactory
     */
    protected $uploaderFactory;

    /**
     * @var \FiloBlu\Storelocator\Model\Stores\Image
     */
    protected $imageModel;
    /**
     * @var \FiloBlu\Storelocator\Model\ImagesFactory
     */
    private $imagesFactory;

    /**
     * @param Action\Context $context
     * @param UploaderFactory $uploaderFactory
     * @param Image $imageModel
     * @param \FiloBlu\Storelocator\Model\ImagesFactory $imagesFactory
     */
    public function __construct(
        Action\Context $context,
        UploaderFactory $uploaderFactory,
        Image $imageModel,
        ImagesFactory $imagesFactory
    ) {
        parent::__construct($context);
        $this->uploaderFactory = $uploaderFactory;
        $this->imageModel = $imageModel;
        $this->imagesFactory = $imagesFactory;
    }

    /**
     * Save action
     *
     * @return ResultInterface
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        /** @var Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($data) {
            /** @var Images $model */
            $model = $this->imagesFactory->create();

            $id = $this->getRequest()->getParam('image_id');

            if ($id) {
                $model->load($id);
            }

            $model->setData($data);

            $this->_eventManager->dispatch(
                'storelocator_image_prepare_save',
                ['image' => $model, 'request' => $this->getRequest()]
            );

            try {
                $imageName = $this->uploadFileAndGetName('image', $this->imageModel->getBaseDir(), $data);
                $model->setImage($imageName);

                $model->save();
                $this->messageManager->addSuccess(__('You saved this image.'));
                $this->_getSession()->setFormData(false);
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['image_id' => $model->getId(), '_current' => true]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (RuntimeException $e) {
                $this->messageManager->addError($e->getMessage());
            } catch (Exception $e) {
                $this->messageManager->addException($e, __('Something went wrong while saving the image.'));
            }

            $this->_getSession()->setFormData($data);
            return $resultRedirect->setPath('*/*/edit', ['image_id' => $this->getRequest()->getParam('image_id')]);
        }
        return $resultRedirect->setPath('*/*/');
    }

    /**
     * @param $input
     * @param $destinationFolder
     * @param $data
     * @return mixed|string
     * @throws \Exception
     */
    public function uploadFileAndGetName($input, $destinationFolder, $data)
    {
        try {
            if (isset($data[$input]['delete'])) {
                return '';
            } else {
                $uploader = $this->uploaderFactory->create(['fileId' => $input]);
                $uploader->setAllowRenameFiles(true);
                $uploader->setFilesDispersion(true);
                $uploader->setAllowCreateFolders(true);
                $result = $uploader->save($destinationFolder);
                return $result['file'];
            }
        } catch (Exception $e) {
            if ($e->getCode() != Uploader::TMP_NAME_EMPTY) {
                throw new Exception($e->getMessage());
            } else {
                if (isset($data[$input]['value'])) {
                    return $data[$input]['value'];
                }
            }
        }
        return '';
    }

    /**
     * {@inheritdoc}
     */
    protected function _isAllowed()
    {
        return $this->_authorization->isAllowed('FiloBlu_Storelocator::storelocator_save');
    }
}
