<?php
/**
 * @author  Magediary
 * @package Magediary_ProductQuestion
 */

namespace Magediary\ProductQuestion\Block\Question;

use Magento\Customer\Model\Context;
use Magento\Customer\Model\Url;
use Magento\Framework\View\Element\Template;

class Form extends Template
{
    /**
     * ProductQuestion data
     *
     * @var \Magediary\ProductQuestion\Helper\Data
     */
    protected $_helperData = null;

    /**
     * Catalog product model
     *
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var \Magento\Framework\Url\EncoderInterface
     */
    protected $urlEncoder;

    /**
     * Message manager interface
     *
     * @var \Magento\Framework\Message\ManagerInterface
     */
    protected $messageManager;

    /**
     * @var \Magento\Framework\App\Http\Context
     */
    protected $httpContext;

    /**
     * @var \Magento\Customer\Model\Url
     */
    protected $customerUrl;

    /**
     * @var array
     */
    protected $jsLayout;

    /**
     * @var \Magento\Framework\Serialize\Serializer\Json
     */
    private $serializer;

    /**
     * @param Template\Context $context
     * @param \Magento\Framework\Url\EncoderInterface $urlEncoder
     * @param \Magediary\ProductQuestion\Helper\Data $helperData
     * @param \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
     * @param \Magento\Framework\Message\ManagerInterface $messageManager
     * @param \Magento\Framework\App\Http\Context $httpContext
     * @param Url $customerUrl
     * @param \Magento\Framework\Serialize\Serializer\Json $serializer
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Url\EncoderInterface $urlEncoder,
        \Magediary\ProductQuestion\Helper\Data $helperData,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Customer\Model\Url $customerUrl,
        \Magento\Framework\Serialize\Serializer\Json $serializer,
        array $data = []
    ) {
        $this->urlEncoder = $urlEncoder;
        $this->_helperData = $helperData;
        $this->productRepository = $productRepository;
        $this->messageManager = $messageManager;
        $this->httpContext = $httpContext;
        $this->customerUrl = $customerUrl;
        $this->serializer = $serializer;
        $this->jsLayout = isset($data['jsLayout']) ? $data['jsLayout'] : [];
        parent::__construct($context, $data);
    }

    /**
     * Initialize question form
     *
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();

        $this->setAllowWriteQuestionFlag(
            $this->httpContext->getValue(Context::CONTEXT_AUTH)
            || $this->_helperData->getConfig('question/question/allow_guest')
        );
        if (!$this->getAllowWriteQuestionFlag()) {
            $queryParam = $this->urlEncoder->encode(
                $this->getProductInfo()->getProductUrl() . '#questions'
            );
            $this->setLoginLink(
                $this->getUrl(
                    'customer/account/login/',
                    [Url::REFERER_QUERY_PARAM_NAME => $queryParam]
                )
            );
        }

        $this->setTemplate('question/form.phtml');
    }

    /**
     * Return config value
     *
     * @return bool
     */
    public function showNickname()
    {
        return $this->_helperData->getConfig('question/question/enable_nickname');
    }

    /**
     * Get customer name
     *
     * @return string
     */
    public function getNickname()
    {
        return $this->httpContext->getValue('customer_name');
    }

    /**
     * Return config value
     *
     * @return bool
     */
    public function isNicknameRequired()
    {
        return $this->_helperData->getConfig('question/question/required_nickname');
    }

    /**
     * Get customer email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->httpContext->getValue('customer_email');
    }

    /**
     * Return config value
     *
     * @return bool
     */
    public function showEmail()
    {
        return $this->_helperData->getConfig('question/question/enable_email');
    }

    /**
     * Return config value
     *
     * @return bool
     */
    public function isEmailRequired()
    {
        return $this->_helperData->getConfig('question/question/required_email');
    }

    /**
     * Get js layout object
     *
     * @return string
     */
    public function getJsLayout()
    {
        return $this->serializer->serialize($this->jsLayout);
    }

    /**
     * Get product info
     *
     * @return \Magento\Catalog\Api\Data\ProductInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getProductInfo()
    {
        return $this->productRepository->getById(
            $this->getProductId(),
            false,
            $this->_storeManager->getStore()->getId()
        );
    }

    /**
     * Get question post action
     *
     * @return string
     */
    public function getAction()
    {
        return $this->getUrl(
            'question/product/post',
            [
                '_secure' => $this->getRequest()->isSecure(),
                'id' => $this->getProductId(),
            ]
        );
    }

    /**
     * Return register URL
     *
     * @return string
     */
    public function getRegisterUrl()
    {
        return $this->customerUrl->getRegisterUrl();
    }

    /**
     * Get product id
     *
     * @return int
     */
    protected function getProductId()
    {
        return $this->getRequest()->getParam('id', false);
    }
}
