<?php
/**
 * Copyright © Autogedal. All rights reserved.
 */
namespace Autogedal\AjaxcartCustom\Plugin\Helper;

use Magento\CatalogInventory\Api\StockStateInterface;
use Magento\Catalog\Model\Product;
use Tigren\Ajaxcart\Helper\Data as AjaxcartHelper;

class DataPlugin
{
    /**
     * @var StockStateInterface
     */
    protected $stockState;

    /**
     * @param StockStateInterface $stockState
     */
    public function __construct(
        StockStateInterface $stockState
    ) {
        $this->stockState = $stockState;
    }

    /**
     * Add custom getStockState method
     *
     * @param AjaxcartHelper $subject
     * @param callable $proceed
     * @param string $method
     * @param array $args
     * @return mixed
     */
    public function around__call(AjaxcartHelper $subject, callable $proceed, $method, $args)
    {
        if ($method === 'getStockState' && isset($args[0]) && $args[0] instanceof Product) {
            return $this->getStockState($args[0]);
        }
        
        return $proceed($method, $args);
    }

    /**
     * Get stock state for product
     *
     * @param Product $product
     * @return float
     */
    protected function getStockState(Product $product)
    {
        return $this->stockState->getStockQty(
            $product->getId(),
            $product->getStore()->getWebsiteId()
        );
    }
}