<?php

namespace FiloBlu\Storelocator\Controller\Adminhtml\Tags;

use Exception;
use FiloBlu\Storelocator\Model\Stores\Image;
use FiloBlu\Storelocator\Model\TagsFactory;
use Magento\Backend\App\Action;
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\TagsFactory
     */
    private $tagsFactory;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory
     * @param \FiloBlu\Storelocator\Model\Stores\Image $imageModel
     * @param \FiloBlu\Storelocator\Model\TagsFactory $tagsFactory
     */
    public function __construct(
        Action\Context $context,
        UploaderFactory $uploaderFactory,
        Image $imageModel,
        TagsFactory $tagsFactory
    ) {
        $this->uploaderFactory = $uploaderFactory;
        $this->imageModel = $imageModel;
        parent::__construct($context);
        $this->tagsFactory = $tagsFactory;
    }

    /**
     * Save action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();
        /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();
        if ($data) {
            /** @var \FiloBlu\Storelocator\Model\Tags $model */
            $model = $this->tagsFactory->create();

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

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

            $model->setData($data);

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

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

                $model->save();
                $this->messageManager->addSuccessMessage(__('You saved this tag.'));
                $this->_getSession()->setFormData(false);
                if ($this->getRequest()->getParam('back')) {
                    return $resultRedirect->setPath('*/*/edit', ['tag_id' => $model->getId(), '_current' => true]);
                }
                return $resultRedirect->setPath('*/*/');
            } catch (LocalizedException $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            } catch (RuntimeException $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            } catch (Exception $e) {
                $this->messageManager->addErrorMessage($e->getMessage());
            }

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

    /**
     * @throws \Exception
     */
    public function uploadFileAndGetName($input, $destinationFolder, $data)
    {
        try {
            if (isset($data[$input]['delete'])) {
                return '';
            }

            $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());
            }

            if (isset($data[$input]['value'])) {
                return $data[$input]['value'];
            }
        }
        return '';
    }

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