<?php

namespace FiloBlu\Esb\Model\Config\Source;

use Magento\Framework\App\ObjectManager;
use Magento\Framework\Data\OptionSourceInterface;
use Magento\InventorySourceSelectionApi\Api\GetSourceSelectionAlgorithmListInterface;

/**
 * Class ShippingSelectionAlgorithm
 * @package FiloBlu\Esb\Model\Config\Source
 */
class ShippingSelectionAlgorithm implements OptionSourceInterface
{
    /** @var array */
    protected $options;
    /**
     * @var GetSourceSelectionAlgorithmListInterface
     */
    private $getSourceSelectionAlgorithmList;

    /**
     * ShippingSelectionAlgorithm constructor.
     */
    public function __construct()
    {
        if(interface_exists(GetSourceSelectionAlgorithmListInterface::class)) {
            $this->getSourceSelectionAlgorithmList = ObjectManager::getInstance()->get(GetSourceSelectionAlgorithmListInterface::class);
        }
    }

    /**
     * @return array
     */
    public function toOptionArray()
    {
        if ($this->options !== null) {
            return $this->options;
        }

        if ($this->getSourceSelectionAlgorithmList === null) {
            return [];
        }

        $algorithmList = $this->getSourceSelectionAlgorithmList->execute();

        foreach ($algorithmList as $algorithm) {
            $this->options[] = ['value' => $algorithm->getCode(), 'label' => $algorithm->getTitle()];
        }

        return $this->options;
    }
}
