<?php

namespace FiloBlu\Refilo\Model\Config;

use FiloBlu\Core\Framework\Model\Mapper;
use FiloBlu\Core\Framework\Model\MapperFactory;
use Magento\Framework\DataObject;
use Magento\Framework\DataObjectFactory;
use Magento\Store\Api\Data\StoreInterface;
use stdClass;

/**
 * Class ConfigProvider
 * @package FiloBlu\Refilo\Model\Config
 */
abstract class AbstractConfigProvider implements ConfigProviderInterface
{
    /**
     * @var DataObjectFactory
     */
    protected $dataObjectFactory;
    /**
     * @var MapperFactory
     */
    private $mapperFactory;

    /**
     * ConfigProvider constructor.
     * @param MapperFactory $mapperFactory
     * @param DataObjectFactory $dataObjectFactory
     */
    public function __construct(MapperFactory $mapperFactory, DataObjectFactory $dataObjectFactory)
    {
        $this->mapperFactory = $mapperFactory;
        $this->dataObjectFactory = $dataObjectFactory;
    }

    /**
     * @param DataObject $configurations
     * @param StoreInterface|null $store
     * @return mixed|void
     */
    public function getConfigs(DataObject $configurations, StoreInterface $store = null)
    {
        /** @var Mapper $mapper */
        $mapper = $this->mapperFactory->create();
        $data = $this->dataObjectFactory->create(['data' => $this->prepareData($configurations, $store)]);

        return $this->setMappings($mapper)
            ->render($data)
            ->toArray();
    }

    /**
     * @param DataObject $configurations
     * @param StoreInterface|null $store
     * @return array
     */
    abstract protected function prepareData(DataObject $configurations, StoreInterface $store = null): array;

    /**
     * @param Mapper $mapper
     * @return Mapper
     */
    abstract protected function setMappings(Mapper $mapper);

    /**
     * @todo Refactor as injected depency
     * @param $config
     * @return array
     */
    public function getListConfig($config)
    {
        $convertedConfig = [];
        $data = unserialize($config);
        foreach ($data as $config) {
            $convertedConfig[] = (array)$config;
        }

        return $convertedConfig;
    }

    /**
     * @param $config
     * @return array
     */
    public function prepareCountryUrlData($config)
    {
        $convertedConfig = [];
        $data = unserialize($config);
        foreach ($data as $countries => $url) {
            $countriesParsed = explode(',',$countries);
            foreach ($countriesParsed as $country){
                $countryObj = new stdClass();
                $countryObj->country = $country;
                $countryObj->url = $url;
                $convertedConfig[] = $countryObj;
            }
        }

        return $convertedConfig;
    }
}
