<?php

declare(strict_types=1);


namespace FiloBlu\ExtBlackbirdMenuManager\Controller\Adminhtml\Menu;

use Exception;
use FiloBlu\ExtBlackbirdMenuManager\Model\Menu\ImporterInterface;
use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;

/**
 *
 */
class PostImport extends Action
{

    /**
     * @var \FiloBlu\ExtBlackbirdMenuManager\Model\Menu\ImporterInterface
     */
    private $importer;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \FiloBlu\ExtBlackbirdMenuManager\Model\Menu\ImporterInterface $importer
     */
    public function __construct(
        Context $context,
        ImporterInterface $importer
    ) {
        parent::__construct($context);
        $this->importer = $importer;
    }

    /**
     * {@inheritdoc}
     */
    public function execute()
    {
        $file = $this->getRequest()
                     ->getFiles()
        ;

        $resultRedirect = $this->resultRedirectFactory->create();
        foreach ($file as $identifier => $dataFile)
        {
            try
            {
                $jsonData = file_get_contents($dataFile['tmp_name']);
                $this->importer->import($jsonData);
                $this->messageManager->addSuccessMessage(__('Contents imported!'));

                return $resultRedirect->setPath('*/*/import');
            } catch (Exception $e)
            {
                $this->messageManager->addErrorMessage($e->getMessage());
                return $resultRedirect->setPath('*/*/import');
            }
        }
        return $resultRedirect->setPath('*/*/import');
    }

}
