<?php

/**
 * Copyright © 2018 Wyomind. All rights reserved.
 * See LICENSE.txt for license details.
 */

namespace Wyomind\ElasticsearchLayeredNavigation\Helper;

use Magento\Catalog\Helper\Product\ProductList;
use Magento\Catalog\Model\Config as CatalogConfig;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Registry;
use Magento\Framework\Stdlib\CookieManagerInterface;
use Wyomind\ElasticsearchLayeredNavigation\Helper\Config;

/**
 * Toolbar helper to get the toolbar configuration
 * @package Wyomind\ElasticsearchLayeredNavigation\Helper
 */
class Toolbar extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var RequestInterface
     */
    protected $request;
    /**
     * @var CookieManagerInterface
     */
    protected $cookieManager;
    /**
     * @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
     */
    protected $cookieMetadataFactory;

    /**
     * Modes available grid/list
     * @var array
     */
    private $availableMode = [];

    /**
     * @var ProductList|null
     */
    protected $productListHelper = null;

    /**
     * @var Config|null
     */
    protected $configHelper = null;

    /**
     * @var CatalogConfig|null
     */
    protected $catalogConfig = null;

    /**
     * Toolbar constructor.
     * @param Context $context
     * @param Registry $registry
     * @param ProductList $productListHelper
     * @param Config $configHelper
     * @param CatalogConfig $catalogConfig
     * @param RequestInterface $request
     * @param CookieManagerInterface $cookieManager
     * @param \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
     */
    public function __construct(
        Context $context,
        Registry $registry,
        ProductList $productListHelper,
        Config $configHelper,
        CatalogConfig $catalogConfig,
        RequestInterface $request,
        CookieManagerInterface $cookieManager,
        \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory $cookieMetadataFactory
    )
    {
        parent::__construct($context);
        $this->_registry = $registry;
        $this->productListHelper = $productListHelper;
        $this->configHelper = $configHelper;
        $this->catalogConfig = $catalogConfig;
        $this->request = $request;
        $this->cookieManager = $cookieManager;
        $this->cookieMetadataFactory = $cookieMetadataFactory;
    }

    /**
     * Get available mode to display the products (grid/list)
     * @return array|null
     */
    public function getModes()
    {
        if ($this->availableMode === []) {
            $this->availableMode = $this->productListHelper->getAvailableViewMode();
        }
        return $this->availableMode;
    }

    /**
     * Is the mode active?
     * @param $mode
     * @return bool
     */
    public function isModeActive($mode)
    {
        return $this->getCurrentMode() == $mode;
    }

    /**
     * Get the available orders for the sorter
     * @return array
     */
    public function getAvailableOrders()
    {
        return $this->catalogConfig->getAttributeUsedForSortByArray();
    }

    /**
     * Get the available limit for the current mode
     * @return array
     */
    public function getAvailableLimit()
    {
        return $this->productListHelper->getAvailableLimit($this->getCurrentMode());
    }


    /**
     * Get the default number of products per page
     * @param null $store
     * @return array
     */
    public function getPerPageDefaultValue($store = null)
    {
        return $this->configHelper->getPerPageDefaultValue($store);
    }

    /**
     * Get the current mode
     */
    public function getCurrentMode()
    {
        $currentMode = "";
        if (isset($_COOKIE['eln_mode'])) {
            $currentMode = $_COOKIE['eln_mode'];
        }
        if (empty($currentMode)) {
            $currentMode = "grid";
        }
        return $currentMode;
    }

    /**
     * Get the current sorter order field
     * @param $type
     * @return string
     */
    public function getCurrentOrder($type)
    {

        if ($this->request->getParam('order')) {
            $orders = array_keys($this->getAvailableOrders());
            if (in_array($this->request->getParam('order'), $orders)) {
                $this->setCookie('eln_order_'.$type, $this->request->getParam('order'));
                return $this->request->getParam('order');
            }
        }

        $currentOrder = "";
        if (isset($_COOKIE['eln_order_'.$type])) {
            $currentOrder = $_COOKIE['eln_order_'.$type];
        }
        if (empty($currentOrder)) {
            if ($type == "search") {
                $currentOrder = "score";
            } else {
                $currentOrder = "position";
            }
        }
        return $currentOrder;
    }

    public function setCookie($key, $value)
    {
        $publicCookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata();
        $publicCookieMetadata->setDurationOneYear();
        $publicCookieMetadata->setPath('/');
        $publicCookieMetadata->setHttpOnly(false);
        $this->cookieManager->setPublicCookie($key, $value, $publicCookieMetadata);
    }

    /**
     * Get the current sorter direction
     * @param $type
     * @return string
     */
    public function getCurrentDirection($type)
    {
        if ($this->request->getParam('dir')) {
            if (in_array($this->request->getParam('dir'), ['desc', 'asc'])) {
                $this->setCookie('eln_dir_'.$type, $this->request->getParam('dir'));
                return $this->request->getParam('dir');
            }
        }

        $currentDirection = "";
        if (isset($_COOKIE['eln_dir_'.$type])) {
            $currentDirection = $_COOKIE['eln_dir_'.$type];
        }
        if (empty($currentDirection)) {
            if ($type == "search") {
                $currentDirection = "desc";
            } else {
                $currentDirection = "asc";
            }
        }
        return $currentDirection;
    }

    /**
     * Get the current number of products per page
     * @return mixed|string
     */
    public function getCurrentPerPage()
    {
        $currentPerPage = "";
        if (isset($_COOKIE['eln_limit'])) {
            $currentPerPage = $_COOKIE['eln_limit'];
        }
        if (empty($currentPerPage)) {
            $currentPerPage = $this->getPerPageDefaultValue()[$this->getCurrentMode()];
        }
        return $currentPerPage;
    }


}
