<?php
/**
 * Webkul Software.
 * 
 * PHP version 7.0+
 *
 * @category  Webkul
 * @package   Webkul_MobikulCore
 * @author    Webkul <support@webkul.com>
 * @copyright 2010-2019 Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html ASL Licence
 * @link      https://store.webkul.com/license.html
 */
namespace Webkul\MobikulCore\Model\Featuredcategories;
use Magento\Eav\Model\Config;
use Webkul\MobikulCore\Model\Featuredcategories;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Session\SessionManagerInterface;
use Webkul\MobikulCore\Model\ResourceModel\Featuredcategories\Collection;
use Webkul\MobikulCore\Model\ResourceModel\Featuredcategories\CollectionFactory as FeaturedcatCollectionFactory;

class DataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider
{

    protected $collection;
    protected $loadedData;
    protected $session;

    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        FeaturedcatCollectionFactory $featuredcategoriesCollectionFactory,
        array $meta = [],
        array $data = []
    ) {
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
        $this->collection = $featuredcategoriesCollectionFactory->create();
        $this->collection->addFieldToSelect("*");
    }

    protected function getSession()
    {
        if ($this->session === null) {
            $this->session = ObjectManager::getInstance()->get("Magento\Framework\Session\SessionManagerInterface");
        }
        return $this->session;
    }

    public function getData()
    {
        if (isset($this->loadedData)) {
            return $this->loadedData;
        }
        $items = $this->collection->getItems();
        foreach ($items as $featuredcategories) {
            $result["featuredcategories"] = $featuredcategories->getData();
            $this->loadedData[$featuredcategories->getId()] = $result;
        }
        $data = $this->getSession()->getFeaturedcategoriesFormData();
        if (!empty($data)) {
            $featuredcategoriesId = isset($data["mobikul_featuredcategories"]["id"]) ? $data["mobikul_featuredcategories"]["id"] : null;
            $this->loadedData[$featuredcategoriesId] = $data;
            $this->getSession()->unsFeaturedcategoriesFormData();
        }
        return $this->loadedData;
    }
}
