<?php

namespace Leadlion\Autogedal\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Amasty\Base\Model\Serializer as JsonSerializer;
use Amasty\Feed\Exceptions\ReindexInProgressException;
use Amasty\Feed\Model\Indexer\Product\ProductFeedProcessor;
use Magento\Framework\Indexer\StateInterface;
use Amasty\Feed\Model\Indexer\Feed\FeedRuleProcessor;
use Magento\Bundle\Model\Product\Type;
use Magento\CatalogInventory\Api\StockConfigurationInterface;
use Magento\CatalogInventory\Model\Spi\StockRegistryProviderInterface;
use Magento\CatalogInventory\Model\Spi\StockStateProviderInterface;

class Config extends AbstractHelper
{
    const BREADCRUMBS_FILTERS = 'leadlion/layer_navigation/filters';
    const ATTRIBUTES_SETS_SKU = 'leadlion/sku_fz_custom_conf/ids';

    /**
     * @var JsonSerializer
     */
    private $jsonSerializer;

    /**
     * @var \Magento\Indexer\Model\Indexer\StateFactory
     */
    protected $stateFactory;
    
    protected $scopeConfig;

    /**
     * @var  Type
     */
    protected $bundleType;

    /**
     * @var StockConfigurationInterface
     */
    protected $stockConfiguration;

    /**
     * @var StockRegistryProviderInterface
     */
    protected $stockRegistryProvider;

    /**
     * @var StockStateProviderInterface
     */
    protected $stockStateProvider;

    public function __construct(
        Context $context,
        JsonSerializer $jsonSerializer,
        \Magento\Indexer\Model\Indexer\StateFactory $stateFactory,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        Type $bundleType,
        StockConfigurationInterface $stockConfiguration,
        StockStateProviderInterface $stockStateProvider,
        StockRegistryProviderInterface $stockRegistryProvider
    ) {
        parent::__construct(
            $context
        );
        $this->stockStateProvider = $stockStateProvider;
        $this->stockRegistryProvider = $stockRegistryProvider;
        $this->stockConfiguration = $stockConfiguration;
        $this->bundleType = $bundleType;
        $this->scopeConfig = $scopeConfig;
        $this->jsonSerializer = $jsonSerializer;
        $this->stateFactory = $stateFactory;
    }

    /**
     * Retrieve stock qty whether product is composite or no
     *
     * @param int $productId
     * @param int $scopeId
     * @return float
     */
    public function getStockQty($product, $scopeId = null)
    {
        if ($product->getTypeId() == \Magento\Bundle\Model\Product\Type::TYPE_CODE) {
            $options = $this->bundleType->getOptionsCollection($product);
            $selections = $this->bundleType->getSelectionsCollection($options->getAllIds(), $product);
        
            foreach ($selections as $selection) {
                $simpleProductId = $selection->getEntityId();
                $defaultSimpleQty = $selection->getSelectionQty();

                $scopeId = $this->stockConfiguration->getDefaultScopeId();
                $stockItem = $this->stockRegistryProvider->getStockItem($simpleProductId, $scopeId);
    
                $simpleQty = $this->stockStateProvider->getStockQty($stockItem);
                if ($simpleQty <= 0 || $simpleQty < $defaultSimpleQty) {
                    return 0;
                }
            }
            return 1;
        } else {
            $scopeId = $this->stockConfiguration->getDefaultScopeId();
            $stockItem = $this->stockRegistryProvider->getStockItem($product->getId(), $scopeId);
    
            return $this->stockStateProvider->getStockQty($stockItem);
        }
        
    }

    public function getAttributesSetsIdsForShowingSku()
    {
        return $this->scopeConfig->getValue(
            self::ATTRIBUTES_SETS_SKU,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            null
        );
    }

    public function getIndexesStatus()
    {
        $productIndexerState = $this->stateFactory->create()
            ->loadByIndexer(ProductFeedProcessor::INDEXER_ID);
        $ruleIndexerState = $this->stateFactory->create()
            ->loadByIndexer(FeedRuleProcessor::INDEXER_ID);

        if (in_array(StateInterface::STATUS_WORKING, [$productIndexerState->getStatus(), $ruleIndexerState->getStatus()])) {
            throw new ReindexInProgressException();
        }

        return true;
    }

    public function getConfig($config_path , $storeId = null) {

        return $this->scopeConfig->getValue($config_path, \Magento\Store\Model\ScopeInterface::SCOPE_STORE , $storeId);
    }
    
    /**
     * @return string
     */
    public function getBreadcrumbsFilters()
    {
        return $this->jsonSerializer->serialize($this->getConfig(self::BREADCRUMBS_FILTERS));
    }
}
