<?php
namespace FiloBlu\Esb\Helper\Format;

use Exception;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\ObjectManagerInterface;

/**
 * Factory class to build Format Helper depending on System Configuration (JSON or XML)
 */
class FormatFactory
{
    /**
     * @var array
     */
    protected $_pluginConfiguration;

    /**
     * @var ScopeConfigInterface
     */
    protected $_scopeConfig;

    /**
     * @var ObjectManagerInterface
     */
    protected $_objectManager;

    /**
     * Constructor
     *
     * @param ObjectManagerInterface $objectManager
     * @param ScopeConfigInterface $scopeConfig
     * @param array $pluginConfiguration
     */
    public function __construct(
        ObjectManagerInterface $objectManager,
        ScopeConfigInterface $scopeConfig,
        $pluginConfiguration = []
    ) {
        $this->_objectManager = $objectManager;
        $this->_scopeConfig = $scopeConfig;
        $this->_pluginConfiguration = $pluginConfiguration;
    }

    /**
     * Creates Format Helper instance depending on System Configuration (JSON or XML)
     * @throws Exception
     * @return FormatInterface
     */
    public function create()
    {
        $configuredFormat = $this->_scopeConfig->getValue('esb/general/format');
        if (array_key_exists($configuredFormat, $this->_pluginConfiguration)) {
            $configuredClass = $this->_pluginConfiguration[$configuredFormat];
            $formatHelper = $this->_objectManager->create($configuredClass);
            if (!($formatHelper instanceof FormatInterface)) {
                throw new Exception(
                    'Object is not instance of FormatInterface'
                );
            }
        } else {
            throw new Exception("Cannot find format class for $configuredFormat");
        }

        return $formatHelper;
    }
}
