<?php

namespace Magetop\Agency\Controller\Adminhtml\Assignproduct;

use Magetop\Agency\Controller\Adminhtml\Assignproduct as ProductController;
use Magento\Framework\Controller\ResultFactory;

class Edit extends ProductController
{
    /**
     * @var \Magento\Backend\Model\Session
     */
    protected $_backendSession;

    /**
     * @var \Magento\Framework\Registry
     */
    protected $_registry;

    /**
     * @var \Magetop\Agency\Model\ProductFactory
     */
    protected $_Product;

    /**
     * @param \Magento\Backend\App\Action\Context $context
     * @param \Magento\Framework\Registry $registry
     * @param \Magetop\Agency\Model\ProductFactory $Product
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\Registry $registry,
        \Magetop\Agency\Model\ItemsFactory $items
    ) {
        $this->_backendSession = $context->getSession();
        $this->_registry = $registry;
        $this->_items = $items;
        parent::__construct($context);
    }

    /**
     * @return \Magento\Backend\Model\View\Result\Page
     */
    public function execute()
    {
        $id = $this->getRequest()->getParam('id');
        $assignProduct = $this->_items->create();
        if ($this->getRequest()->getParam('id')) {
            $assignProduct->load($this->getRequest()->getParam('id'));
        }
        if (!$assignProduct->getId()) {
            $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
            $this->messageManager->add("Product not found.");
            return $resultRedirect->setPath('*/*/');
        }
        $data = $this->_backendSession->getFormData(true);
        if (!empty($data)) {
            $assignProduct->setData($data);
        }
        $this->_registry->register('assign_product', $assignProduct);
        $resultPage = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
        $resultPage->setActiveMenu('Magetop_Agency::menu');
        $resultPage->getConfig()->getTitle()->prepend(__('Product'));
        $resultPage->getConfig()->getTitle()->prepend(
            $assignProduct->getId() ? $assignProduct->getTitle() : __('New Image')
        );
        $block = 'Magetop\Agency\Block\Adminhtml\Product\Edit';
        $content = $resultPage->getLayout()->createBlock($block);
        $resultPage->addContent($content);
        return $resultPage;
    }
}
