<?php

namespace Leadlion\AutoRelated\Block\Product\ProductList;

use Countable;

class Upsell extends \Smartwave\Filterproducts\Block\UpsellList //implements  Countable
{

    /**
    * @var \Magento\Core\Model\Factory\Helper
    */
    protected $_helper;

    /**
    * @var \Magento\Store\Model\StoreManagerInterface
    */
    protected $_storeManager;

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

    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Checkout\Model\ResourceModel\Cart $checkoutCart,
        \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Framework\Module\Manager $moduleManager,
        \Leadlion\AutoRelated\Helper\Data $helper,
        \Magento\Framework\Url\Helper\Data $urlHelper,
        array $data = []
    ) {
        $this->_helper = $helper;
        $this->_storeManager = $context->getStoreManager();
        $this->urlHelper = $urlHelper;
        
        parent::__construct(
            $context,
            $checkoutCart,
            $catalogProductVisibility,
            $checkoutSession,
            $moduleManager,
            $data
        );

        // Only cache if we have something thats keyable..
        $_time = $this->_helper->get_cache_lifetime();

        if ($_time > 0 && $cacheKey = $this->_cacheKey()) {
            $this->addData([
                'cache_lifetime'    => $_time,
                'cache_tags'        => [\Magento\Store\Model\Store::CACHE_TAG],
                'cache_key'         => $cacheKey,
            ]);
        }
    }

    public function getAddToCartPostParams(\Magento\Catalog\Model\Product $product)
    {
        $url = $this->getAddToCartUrl($product);
        return [
            'action' => $url,
            'data' => [
                'product' => $product->getEntityId(),
                \Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED =>
                    $this->urlHelper->getEncodedUrl($url),
            ]
        ];
    }

    protected function _cacheKey()
    {
        $product = $this->getProduct();

        if ($product) {
            return get_class() . '::' . $this->_storeManager->getStore()->getCode() . '::' . $product->getId();
        }

        return false;
    }

    public function getIdentities()
    {
        $identities = [];
        //Bugfix: Warning: Invalid argument supplied for foreach()
        if (is_array($this->getItems()) || is_object($this->getItems())) {
            foreach ($this->getItems() as $item) {
                $identities = array_merge($identities, $item->getIdentities());
            }
        }
        return $identities;
    }
}
