<?php
declare(strict_types=1);

namespace Webkul\MobikulGraphQL\Model\Resolver;
if (!defined('DS')) {
    define('DS', DIRECTORY_SEPARATOR);
}

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;

/**
 * HomePageData resolver
 */
class HomePageData implements \Magento\Framework\GraphQl\Query\ResolverInterface
{

    protected $helper;
    protected $baseDir;
    protected $helperCatalog;
    protected $featuredCategories;
    protected $categoryResourceModel;
    protected $_storeManager;
    protected $categoryRepository;

    public function __construct(
        RequestInterface $requestInterface,
        \Magento\Cms\Model\Page $cmsPage,
        \Magento\Store\Model\Store $store,
        \Webkul\MobikulCore\Helper\Data $helper,
        \Magento\Framework\Escaper $escaper,
        \Magento\Review\Model\Rating $rating,
        \Magento\Review\Model\Review $review,
        \Magento\Eav\Model\Config $eavConfig,
        \Magento\Quote\Model\Quote $quoteModel,
        \Magento\Catalog\Helper\Data $taxHelper,
        \Webkul\MobikulCore\Model\Layer $mobikulLayer,
        \Magento\Framework\Registry $coreRegistry,
        \Magento\Catalog\Helper\Image $imageHelper,
        \Magento\Store\Model\App\Emulation $emulate,
        \Magento\Catalog\Model\Config $catalogConfig,
        \Webkul\MobikulCore\Helper\Catalog $helperCatalog,
        \Magento\Checkout\Helper\Data $checkoutHelper,
        \Webkul\MobikulCore\Model\Bannerimage $bannerImage,
        \Magento\Framework\Locale\Format $localeFormat,
        \Magento\Framework\App\Action\Context $context,
        \Webkul\MobikulCore\Model\UserImage $customerImage,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Magento\Catalog\Model\Layer\Search $searchLayer,
        \Magento\SendFriend\Model\SendFriend $sendFriend,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Catalog\Model\CategoryFactory $category,
        \Magento\Search\Model\QueryFactory $queryFactory,
        \Magento\Framework\Filesystem\DirectoryList $dir,
        \Magento\Catalog\Helper\Category $categoryHelper,
        \Magento\Customer\Model\Visitor $customerVisitor,
        \Magento\Catalog\Helper\Product\Compare $compare,
        \Magento\Wishlist\Model\WishlistFactory $wishlist,
        \Webkul\MobikulCore\Model\Category\Tree $categoryTree,
        \Magento\Framework\Stdlib\DateTime\DateTime $date,
        \Magento\Downloadable\Helper\File $downloadHelper,
        \Magento\Downloadable\Model\Sample $downloadSample,
        \Magento\Catalog\Block\Product\Price $productPrice,
        \Magento\Store\Model\WebsiteFactory $websiteManager,
        \Magento\CatalogInventory\Helper\Stock $stockFilter,
        \Magento\Catalog\Helper\Output $catalogHelperOutput,
        \Magento\Catalog\Model\Layer\Resolver $layerResolver,
        \Magento\Catalog\Model\Product\Option $productOption,
        \Magento\Downloadable\Model\LinkFactory $linkFactory,
        \Magento\Bundle\Model\Product\Price $bundlePriceModel,
        // \Webkul\MobikulCore\Block\Configurable $configurableBlock,
        \Magento\Framework\Pricing\Helper\Data $pricingHelper,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Framework\App\ResourceConnection $connection,
        \Webkul\MobikulCore\Model\CarouselFactory $carouselFactory,
        \Magento\Catalog\Block\Product\ListProduct $listProduct,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Cms\Model\Template\FilterProvider $filterProvider,
        \Magento\Store\Model\StoreManagerInterface $storeInterface,
        \Magento\Catalog\Block\Product\ProductList\Toolbar $toolbar,
        \Magento\Catalog\Model\Layer\Filter\Category $categoryLayer,
        \Magento\Catalog\Model\Product\Visibility $productVisibility,
        \Webkul\MobikulCore\Model\FeaturedcategoriesFactory $featuredCategories,
        \Magento\CatalogSearch\Model\Advanced $advancedCatalogSearch,
        \Magento\Catalog\Model\Layer\Filter\Attribute $filterAttribute,
        \Webkul\MobikulCore\Model\NotificationFactory $mobikulNotification,
        \Magento\Framework\Locale\CurrencyInterface $currencyInterface,
        \Magento\Downloadable\Block\Catalog\Product\Links $productLinks,
        \Magento\Cms\Model\ResourceModel\Page\Collection $cmsCollection,
        \Magento\Catalog\Block\Product\View\Options $productOptionBlock,
        \Webkul\MobikulCore\Model\CarouselimageFactory $carouselImageFactory,
        \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
        \Webkul\MobikulCore\Model\CategoryimagesFactory $categoryImageFactory,
        \Magento\Catalog\Model\ResourceModel\Product $productResourceModel,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Downloadable\Block\Catalog\Product\Samples $productSample,
        \Magento\GroupedProduct\Model\Product\Type\Grouped $groupedProduct,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry,
        \Magento\Catalog\Block\Product\Compare\ListCompare $compareListBlock,
        \Magento\Catalog\Model\Layer\Filter\AttributeFactory $layerAttribute,
        \Magento\Catalog\Model\ResourceModel\Category $categoryResourceModel,
        \Magento\Catalog\Model\Product\Attribute\Source\Status $productStatus,
        \Magento\Catalog\Model\Product\Compare\ItemFactory $compareItemFactory,
        \Webkul\MobikulCore\Model\ResourceModel\Layer\Filter\Price $mobikulLayerPrice,
        \Magento\CatalogSearch\Model\ResourceModel\Search\Collection $searchCollection,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollection,
        \Magento\Catalog\Model\ResourceModel\Product\Collection $productResourceCollection,
        \Magento\Catalog\Model\Layer\Category\FilterableAttributeList $filterableAttributes,
        \Magento\Catalog\Model\Layer\Filter\DataProvider\PriceFactory $filterPriceDataprovider,
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        \Magento\Catalog\Model\ResourceModel\Layer\Filter\AttributeFactory $layerFilterAttributeResource,
        \Magento\Catalog\Model\ResourceModel\Product\Compare\Item\CollectionFactory $compareItemCollectionFactory,
        \Magento\Catalog\Model\CategoryRepository $categoryRepository,
        \Magento\UrlRewrite\Model\UrlRewrite $urlRewrite
        
        
    ) {
        $this->_request = $requestInterface;
        $this->date                         = $date;
        $this->store                        = $store;
        $this->helper                       = $helper;
        $this->rating                       = $rating;
        $this->review                       = $review;
        $this->escaper                      = $escaper;
        $this->compare                      = $compare;
        $this->baseDir                      = $dir->getPath("media");
        $this->toolbar                      = $toolbar;
        $this->cmsPage                      = $cmsPage;
        $this->emulate                      = $emulate;
        $this->category                     = $category;
        $this->wishlist                     = $wishlist;
        $this->taxHelper                    = $taxHelper;
        $this->eavConfig                    = $eavConfig;
        $this->connection                   = $connection;
        $this->sendFriend                   = $sendFriend;
        $this->localeDate                   = $localeDate;
        $this->quoteModel                   = $quoteModel;
        $this->jsonHelper                   = $jsonHelper;
        $this->searchLayer                  = $searchLayer;
        $this->linkFactory                  = $linkFactory;
        $this->listProduct                  = $listProduct;
        $this->bannerImage                  = $bannerImage;
        $this->stockFilter                  = $stockFilter;
        $this->imageHelper                  = $imageHelper;
        $this->catalogLayer                 = $layerResolver->get();
        $this->categoryTree                 = $categoryTree;
        $this->localeFormat                 = $localeFormat;
        $this->eventManager                 = $eventManager;
        $this->queryFactory                 = $queryFactory;
        $this->mobikulLayer                 = $mobikulLayer;
        $this->coreRegistry                 = $coreRegistry;
        $this->productLinks                 = $productLinks;
        $this->productPrice                 = $productPrice;
        $this->productSample                = $productSample;
        $this->helperCatalog                = $helperCatalog;
        $this->customerImage                = $customerImage;
        $this->productStatus                = $productStatus;
        $this->categoryLayer                = $categoryLayer;
        $this->pricingHelper                = $pricingHelper;
        $this->catalogConfig                = $catalogConfig;
        $this->cmsCollection                = $cmsCollection;
        $this->productOption                = $productOption;
        $this->layerResolver                = $layerResolver;
        $this->stockRegistry                = $stockRegistry;
        $this->categoryHelper               = $categoryHelper;
        $this->groupedProduct               = $groupedProduct;
        $this->downloadHelper               = $downloadHelper;
        $this->layerAttribute               = $layerAttribute;
        $this->downloadSample               = $downloadSample;
        $this->storeInterface               = $storeInterface;
        $this->websiteManager               = $websiteManager;
        $this->checkoutHelper               = $checkoutHelper;
        $this->productFactory               = $productFactory;
        $this->filterProvider               = $filterProvider;
        $this->customerSession              = $customerSession;
        $this->filterAttribute              = $filterAttribute;
        $this->carouselFactory              = $carouselFactory;
        $this->customerVisitor              = $customerVisitor;
        $this->customerFactory              = $customerFactory;
        $this->bundlePriceModel             = $bundlePriceModel;
        $this->compareListBlock             = $compareListBlock;
        $this->searchCollection             = $searchCollection;
        $this->currencyInterface            = $currencyInterface;
        // $this->configurableBlock            = $configurableBlock;
        $this->mobikulLayerPrice            = $mobikulLayerPrice;
        $this->productRepository            = $productRepository;
        $this->productVisibility            = $productVisibility;
        $this->productCollection            = $productCollection;
        $this->featuredCategories           = $featuredCategories;
        $this->compareItemFactory           = $compareItemFactory;
        $this->productOptionBlock           = $productOptionBlock;
        $this->catalogHelperOutput          = $catalogHelperOutput;
        $this->mobikulNotification          = $mobikulNotification;
        $this->categoryImageFactory         = $categoryImageFactory;
        $this->carouselImageFactory         = $carouselImageFactory;
        $this->filterableAttributes         = $filterableAttributes;
        $this->productResourceModel         = $productResourceModel;
        $this->advancedCatalogSearch        = $advancedCatalogSearch;
        $this->categoryResourceModel        = $categoryResourceModel;
        $this->filterPriceDataprovider      = $filterPriceDataprovider;
        $this->categoryCollectionFactory    = $categoryCollectionFactory;
        $this->productResourceCollection    = $productResourceCollection;
        $this->layerFilterAttributeResource = $layerFilterAttributeResource;
        $this->compareItemCollectionFactory = $compareItemCollectionFactory;
        $this->categoryRepository = $categoryRepository;
        $this->_urlRewrite = $urlRewrite;
        
    }

    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        $this->wholeData = $args;
        $this->wholeData["storeId"] = 1;
        $this->verifyRequest();
        $homePageData = [];
        $homePageData["categoriesData"]['data'] = $this->getCategoriesData();
        $homePageData["categoriesData"]['backgroundImageUrl'] = $this->getAsideBackgroundImage();
        $homePageData["featuredCategories"] = array_values($this->getFeaturedCategoriesData(1, 144, 144));
        $homePageData["newDeals"] = array_values($this->getNewDeals()['carousel']);
        // $homePageData["newDeals"] = array_values($this->getNewDeals());
        $homePageData["featuredDeals"] = array_values($this->getFeaturedDeals()['carousel']);
        $homePageData["hotDeals"] = array_values($this->getHotDeals()['carousel']);
        $homePageData["craousel"]['product'] = array_values($this->getImageNProductCarousel()['carousel']['product']);
        $homePageData["craousel"]['image'] = array_values($this->getImageNProductCarousel()['carousel']['image']);
        // echo "<pre>";
        // print_r($homePageData);
        // die;
        return $homePageData;
    }

    public function getAsideBackgroundImage()
    {
        return $this->helper->getBaseUrl()."pub/media/blur-bg@3x.png";
    }

    /**
     * Function to add category data to return array
     *
     * @return null
     */
    protected function getCategoriesData()
    {
        $categoryImages = $this->getCategoryImages();
        $catCollection = $this->categoryCollectionFactory->create()
            ->addAttributeToSelect("*")
            ->addFieldToFilter("level", "2");
        $categories = [];
        foreach ($catCollection as $cc) {
            if (array_key_exists($cc->getEntityId(), $categoryImages)) {
                $categories[] = [
                    "id" => $cc->getEntityId(),
                    "name" => $cc->getName(),
                    "banner" => $categoryImages[$cc->getEntityId()]["banner"],
                    "thumbnail" => $categoryImages[$cc->getEntityId()]["thumbnail"],
                    "hasChildren" => $cc->getChildrenCount() > 0 ? true:false,
                    "bannerDominantColor" => $categoryImages[$cc->getEntityId()]["bannerDominantColor"],
                    "thumbnailDominantColor" => $categoryImages[$cc->getEntityId()]["thumbnailDominantColor"],
                    "urlRewrite" => $this->getUrlRewrite($this->storeId, \Magento\UrlRewrite\Controller\Adminhtml\Url\Rewrite::ENTITY_TYPE_CATEGORY, $cc->getEntityId())
                ];
            } else {
                $categories[] = [
                    "id" => $cc->getEntityId(),
                    "name" => $cc->getName(),
                    "hasChildren" => $cc->getChildrenCount() > 0 ? true:false,
                    "thumbnail" => $this->helper->getBaseUrl()."pub/media/icon4.png",
                    "urlRewrite" => $this->getUrlRewrite($this->storeId, \Magento\UrlRewrite\Controller\Adminhtml\Url\Rewrite::ENTITY_TYPE_CATEGORY, $cc->getEntityId())
                ];
            }
        }
        return $categories;
        $this->returnArray["categories"] = $categories;
    }

    /**
     * Function to get categories Images
     *
     * @return array
     */
    protected function getCategoryImages()
    {
        $categoryImages = [];
        $categoryImgCollection = $this->categoryImageFactory
            ->create()
            ->getCollection()
            ->addFieldToFilter("store_id", ["in"=>[0, $this->storeId]]);   
        foreach ($categoryImgCollection as $categoryImage) {
            if ($categoryImage->getBanner() != "" && $categoryImage->getIcon() != "") {
                $eachCategoryImage["id"] = $categoryImage->getCategoryId();
                if ($categoryImage->getIcon() != "") {
                    $basePath = $this->baseDir.DS."mobikul".DS."categoryimages".DS."icon".DS.$categoryImage->getIcon();
                    $newUrl = "";
                    if (is_file($basePath)) {
                        $newPath = $this->baseDir.DS."mobikulresized".DS."144x144".DS."categoryimages".DS."icon".DS.$categoryImage->getIcon();
                        $this->helperCatalog->resizeNCache($basePath, $newPath, 144, 144);
                        $newUrl = $this->helper->getBaseUrl()."pub/media/"."mobikulresized".DS."144x144".DS."categoryimages".DS."icon".DS.$categoryImage->getIcon();
                    }
                    $eachCategoryImage["thumbnail"] = $newUrl;
                    $eachCategoryImage["thumbnailDominantColor"] = $this->helper->getDominantColor($newUrl);
                }
                if ($categoryImage->getBanner() != "") {
                    $basePath = $this->baseDir.DS."mobikul".DS."categoryimages".DS."banner".DS.$categoryImage->getBanner();
                    $newUrl = "";
                    if (is_file($basePath)) {
                        $newPath = $this->baseDir.DS."mobikulresized".DS.$this->bannerWidth."x".$this->height.DS."categoryimages".DS."banner".DS.$categoryImage->getBanner();
                        $this->helperCatalog->resizeNCache($basePath, $newPath, $this->bannerWidth, $this->height);
                        $newUrl = $this->helper->getBaseUrl()."pub/media/"."mobikulresized".DS.$this->bannerWidth."x".$this->height.DS."categoryimages".DS."banner".DS.$categoryImage->getBanner();
                    }
                    $eachCategoryImage["banner"] = $newUrl;
                    $eachCategoryImage["bannerDominantColor"] = $this->helper->getDominantColor($newUrl);
                }
                
                $categoryImages[$eachCategoryImage["id"]] = $eachCategoryImage;
            }
        }
        return $categoryImages;
    }    

    public function verifyRequest()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
        if ($this->_request->getMethod() == "POST") {
            $this->url = $this->wholeData["url"] ?? "";
            $this->eTag = $this->wholeData["eTag"] ?? "";
            $this->width = $this->wholeData["width"] ?? 1000;
            $this->storeId = $this->wholeData["storeId"] ?? 0;
            $this->quoteId = $this->wholeData["quoteId"] ?? 0;
            $this->mFactor = $this->wholeData["mFactor"] ?? 1;
            $this->mFactor = $this->helper->calcMFactor($this->mFactor);
            $this->websiteId = $this->wholeData["websiteId"] ?? 1;
            $this->isFromUrl = $this->wholeData["isFromUrl"] ?? 0;
            $this->customerToken = $this->wholeData["customerToken"] ?? "";
            $this->currency = $this->wholeData["currency"] ?? "";
            $this->customerId = $objectManager->create('Magento\Integration\Model\Oauth\Token')->loadByToken($this->customerToken)->getData('customer_id');
            if ($this->websiteId == 0 && $this->storeId == 0) {
                throw new \Exception(__("Invalid Website Id"));
            }
            if (!$this->customerId && $this->customerToken != "") {
                $this->returnArray["message"] = __("Customer you are requesting does not exist, so you need to logout.");
                $this->returnArray["otherError"] = "customerNotExist";
                $this->customerId = 0;
            } elseif ($this->customerId != 0) {
                $this->customer = $this->customerFactory->create()->load($this->customerId);
                $this->customerSession->setCustomerId($this->customerId);
            }
            // $this->height = $this->helper->getValidDimensions($this->mFactor, 2*($this->width/3));
            $this->bannerWidth = $this->helper->getValidDimensions($this->mFactor, $this->width);
            $this->height = $this->helper->getValidDimensions($this->mFactor, 2*($this->width/3));
            // $this->height = $this->mFactor * (2*($this->width/6));
            // $this->width = $this->mFactor * (3*($this->width/6));
        } else {
            throw new \Exception(__("Invalid Request"));
        }
    }
    public function getFeaturedCategoriesData($storeId, $width, $height)
    {
        $featuredCategoryCollection = $this->featuredCategories
            ->create()
            ->getCollection()
            ->addFieldToFilter("status", 1)
            ->addFieldToFilter("store_id", ["in"=>[0, $storeId]])
            ->setOrder("sort_order", "ASC");
        $featuredCategories = [];
        foreach ($featuredCategoryCollection as $eachCategory) {
            $newUrl   = "";
            $basePath = $this->baseDir.DS.$eachCategory->getFilename();
            $oneCategory = [];
            if (is_file($basePath)) {
                $newPath = $this->baseDir.DS."mobikulresized".DS.$width."x".$height.DS.$eachCategory->getFilename();
                $this->helperCatalog->resizeNCache($basePath, $newPath, $width, $height);
                // $newUrl  = $this->helper->getUrl("media")."mobikulresized".DS.$width."x".$height.DS.$eachCategory->getFilename();
                $newUrl  = $this->helper->getBaseUrl()."pub/media/"."mobikulresized".DS.$width."x".$height.DS.$eachCategory->getFilename();
            }
            $oneCategory["url"] = $this->getCategoryUrl($eachCategory->getCategoryId());
            $oneCategory["imageUrl"] = $newUrl;
            $oneCategory["url_rewrite"] = $this->getUrlRewrite($storeId, \Magento\UrlRewrite\Controller\Adminhtml\Url\Rewrite::ENTITY_TYPE_CATEGORY, $eachCategory->getCategoryId());
            // $oneCategory['dominantColor'] = $this->helper->getDominantColor($newUrl);
            $oneCategory["categoryId"] = $eachCategory->getCategoryId();
            $oneCategory["categoryName"] = $this->categoryResourceModel->getAttributeRawValue($eachCategory->getCategoryId(), "name", $storeId);
            if (is_array($oneCategory["categoryName"])) {
                continue;
            }
            if ($eachCategory->getCategoryId()) {
                $featuredCategories[] = $oneCategory;
            }
        }
        return $featuredCategories;
    }

    protected function getHotDeals()
    {
        $this->returnArray = [];
        $productList = [];
        $todayStartOfDayDate = $this->localeDate->date()->setTime(0, 0, 0)->format("Y-m-d H:i:s");
        $todayEndOfDayDate = $this->localeDate->date()->setTime(23, 59, 59)->format("Y-m-d H:i:s");
        $hotDealCollection = $this->productCollection->create()
            ->setVisibility($this->productVisibility->getVisibleInSiteIds())
            ->addMinimalPrice()
            ->addFinalPrice()
            ->addTaxPercents()
            ->addAttributeToSelect("image")
            ->addAttributeToSelect("thumbnail")
            ->addAttributeToSelect("small_image")
            ->addAttributeToSelect("special_from_date")
            ->addAttributeToSelect("special_to_date")
            ->addAttributeToSelect($this->catalogConfig->getProductAttributes());
        $hotDealCollection->addStoreFilter()
            ->addAttributeToFilter(
                "special_from_date", ["or"=>[
                    0=>["date"=>true, "to"=>$todayEndOfDayDate],
                    1=>["is"=>new \Zend_Db_Expr("null")]]
                ], "left"
            )
            ->addAttributeToFilter(
                "special_to_date", ["or"=>[
                    0=>["date"=>true, "from"=>$todayStartOfDayDate],
                    1=>["is"=>new \Zend_Db_Expr("null")]]
                ], "left"
            )
            ->addAttributeToFilter(
                [["attribute"=>"special_from_date", "is"=>new \Zend_Db_Expr("not null")],
                ["attribute"=>"special_to_date", "is"=>new \Zend_Db_Expr("not null")]]
            );
        if ($this->helperCatalog->showOutOfStock() == 0) {
            $this->stockFilter->addInStockFilterToCollection($hotDealCollection);
        }
        $hotDealCollection->setPageSize(5)->setCurPage(1);
        foreach ($hotDealCollection as $eachProduct) {
            // $productList[] = $this->helperCatalog->getOneProductRelevantData($eachProduct, $this->storeId, $this->width, $this->customerId);
            $productList[] = $this->helperCatalog->getOneProductRelevantData($eachProduct, $this->storeId, $this->width, $this->customerId);
        }
        $carousel = [];
        $carousel["id"] = "hotDeals";
        $carousel["type"] = "product";
        $carousel["label"] = __("Hot Deals");
        $carousel["productList"] = $productList;
        if (count($carousel["productList"])) {
            $this->returnArray["carousel"][] = $carousel;
        }
        return $this->returnArray;
    }

    protected function getFeaturedDeals()
    {
        $this->returnArray = [];
        $productList = [];
        $collection = new \Magento\Framework\DataObject();
        if ($this->helper->getConfigData("mobikul/configuration/featuredproduct") == 1) {
            $collection = $this->productCollection->create()->addAttributeToSelect($this->catalogConfig->getProductAttributes());
            $collection->getSelect()->order("rand()");
            $collection->addAttributeToFilter("status", ["in"=>$this->productStatus->getVisibleStatusIds()]);
            $collection->setVisibility($this->productVisibility->getVisibleInSiteIds());
            if ($this->helperCatalog->showOutOfStock() == 0) {
                $this->stockFilter->addInStockFilterToCollection($collection);
            }
            $collection->setPage(1, 5)->load();
        } else {
            $collection = $this->productCollection->create()
                ->setStore($this->storeId)
                ->addAttributeToSelect($this->catalogConfig->getProductAttributes())
                ->addAttributeToSelect("as_featured")
                ->addAttributeToSelect("image")
                ->addAttributeToSelect("thumbnail")
                ->addAttributeToSelect("small_image")
                ->addAttributeToSelect("visibility")
                ->addStoreFilter()
                ->addAttributeToFilter("status", ["in"=>$this->productStatus->getVisibleStatusIds()])
                ->setVisibility($this->productVisibility->getVisibleInSiteIds())
                ->addAttributeToFilter("as_featured", 1);
            if ($this->helperCatalog->showOutOfStock() == 0) {
                $this->stockFilter->addInStockFilterToCollection($collection);
            }
            $collection->setPageSize(5)->setCurPage(1);
        }
        foreach ($collection as $eachProduct) {
            $productList[] = $this->helperCatalog->getOneProductRelevantData($eachProduct, $this->storeId, $this->width, $this->customerId);
        }
        $carousel = [];
        $carousel["id"] = "featuredProduct";
        $carousel["type"] = "product";
        $carousel["label"] = __("Featured Products");
        $carousel["productList"] = $productList;
        if (count($carousel["productList"])) {
            $this->returnArray["carousel"][] = $carousel;
        }

        return $this->returnArray;
    }

    /**
     * Function to get New deals 
     * Set New deals to return array
     *
     * @return none
     */
    protected function getNewDeals()
    {
        $this->returnArray = [];
        $productList = [];
        // $todayStartOfDayDate = $this->localeDate->date()->setTime(0, 0, 0)->format("Y-m-d H:i:s");
        $todayStartOfDayDate = '2019-03-27 23:59:59';
        $todayEndOfDayDate = '2019-05-27 23:59:59';
        // $todayEndOfDayDate = $this->localeDate->date()->setTime(23, 59, 59)->format("Y-m-d H:i:s");
        $newProductCollection = $this->productCollection->create()
            ->setVisibility($this->productVisibility->getVisibleInSiteIds())
            ->addFinalPrice()
            ->addTaxPercents()
            ->addAttributeToSelect($this->catalogConfig->getProductAttributes())
            ->addStoreFilter()
            ->addMinimalPrice()
            ->addAttributeToFilter(
                "news_from_date", ["or"=>[
                    0=>["date"=>true, "to"=>$todayEndOfDayDate],
                    1=>["is"=>new \Zend_Db_Expr("null")]]
                ], "left"
            )
            ->addAttributeToFilter(
                "news_to_date", ["or"=>[
                    0=>["date"=>true, "from"=>$todayStartOfDayDate],
                    1=>["is"=>new \Zend_Db_Expr("null")]]
                ], "left"
            )
            ->addAttributeToFilter(
                [["attribute"=>"news_from_date", "is"=>new \Zend_Db_Expr("not null")],
                ["attribute"=>"news_to_date", "is"=>new \Zend_Db_Expr("not null")]]
            )
            ->addAttributeToSelect("image")
            ->addAttributeToSelect("thumbnail")
            ->addAttributeToSelect("small_image")
            ->addAttributeToSort("news_from_date", "desc");
        if ($this->helperCatalog->showOutOfStock() == 0) {
            $this->stockFilter->addInStockFilterToCollection($newProductCollection);
        }
        $newProductCollection->setPageSize(5)->setCurPage(1);
        foreach ($newProductCollection as $eachProduct) {
            // $productList[] = $this->helperCatalog->getOneProductRelevantData($eachProduct, $this->storeId, $this->width, $this->customerId);
            $productList[] = $this->helperCatalog->getOneProductRelevantData($eachProduct, $this->storeId, $this->width, $this->customerId);
        }
        $carousel = [];
        $carousel["id"] = "newProduct";
        $carousel["type"] = "product";
        $carousel["label"] = __("New Products");
        $carousel["productList"] = $productList;
        if (count($carousel["productList"])) {
            $this->returnArray["carousel"][] = $carousel;
        }
        return $this->returnArray;
    }

    /**
     * Function to get Image and Product Carousel
     * Set carousels to return array
     *
     * @return none
     */
    protected function getImageNProductCarousel()
    {
        $this->returnArray = [];
        $collection = $this->carouselFactory->create()->getCollection()
            ->addFieldToFilter("status", 1)
            ->addFieldToFilter("store_id", ["in" => [$this->storeId, 0]])
            // ->addFieldToFilter("store_id", ["in" => [1, 0]])
            ->setOrder("sort_order", "ASC");  
        foreach ($collection as $eachCarousel) {
            if ($eachCarousel->getType() == 2) {
                $oneCarousel = [];
                $productList = [];
                $oneCarousel["id"] = $eachCarousel->getId();
                $oneCarousel["type"] = "product";
                $oneCarousel["label"] = $eachCarousel->getTitle();
                if ($eachCarousel->getColorCode()) {
                    $oneCarousel["color"] = $eachCarousel->getColorCode();
                }
                if ($eachCarousel->getFilename()) {
                    // $filePath = $this->helper->getUrl("media")."mobikul/carousel/".$eachCarousel->getFilename();
                    $filePath = $this->helper->getBaseUrl()."pub/media/mobikul/carousel/".$eachCarousel->getFilename();
                    $oneCarousel["image"] = $filePath;
                    $oneCarousel["dominantColor"] = $this->helper->getDominantColor($filePath);
                }
                // $oneCarousel["order"] = $eachCarousel->getSortOrder();
                $selectedProdctIds = explode(",", $eachCarousel->getProductIds());
                $productCollection = $this->productCollection->create()
                    ->addAttributeToSelect($this->catalogConfig->getProductAttributes())
                    ->addAttributeToSelect("image")
                    ->addAttributeToSelect("thumbnail")
                    ->addAttributeToSelect("small_image")
                    ->addAttributeToFilter("entity_id", ["in"=>$selectedProdctIds])
                    // ->setVisibility($this->productVisibility->getVisibleInSiteIds())
                    ->addStoreFilter();
                if ($this->helperCatalog->showOutOfStock() == 0) {
                    $this->stockFilter->addInStockFilterToCollection($productCollection);
                }
                $productCollection->setPageSize(5)->setCurPage(1);
                foreach ($productCollection as $eachProduct) {
                    // $productList[] = $this->helperCatalog->getOneProductRelevantData($eachProduct, $this->storeId, $this->width, $this->customerId);
                    $productList[] = $this->helperCatalog->getOneProductRelevantData($eachProduct, $this->storeId, $this->width, $this->customerId);
                }
                $oneCarousel["productList"] = $productList;
                if (count($oneCarousel["productList"])) {
                    $this->returnArray["carousel"]['product'][] = $oneCarousel;
                }
            } else {
                $banners = [];
                $oneCarousel = [];
                $oneCarousel["type"] = "image";
                $oneCarousel["label"] = $eachCarousel->getTitle();
                if ($eachCarousel->getColorCode()) {
                    $oneCarousel["color"] = $eachCarousel->getColorCode();
                }
                if ($eachCarousel->getFilename()) {
                    $filePath = $this->helper->getUrl("media")."mobikul/carousel/".$eachCarousel->getFilename();
                    $filePath = $this->helper->getBaseUrl()."pub/media/mobikul/carousel/".$eachCarousel->getFilename();
                    $oneCarousel["image"] = $filePath;
                    $oneCarousel["dominantColor"] = $this->helper->getDominantColor($filePath);
                }
                // $oneCarousel["order"] = $eachCarousel->getSortOrder();
                $sellectedBanners = explode(",", $eachCarousel->getImageIds());
                $carouselImageColelction = $this->carouselImageFactory->create()->getCollection()->addFieldToFilter("id", ["in"=>$sellectedBanners]);
                foreach ($carouselImageColelction as $each) {
                    $oneBanner = [];
                    $newUrl = "";
                    $basePath = $this->baseDir.DS.$each->getFilename();
                    if (is_file($basePath)) {
                        $newPath = $this->baseDir.DS."mobikulresized".DS.$this->bannerWidth."x".$this->height.DS.$each->getFilename();
                        $this->helperCatalog->resizeNCache($basePath, $newPath, $this->bannerWidth, $this->height);
                        $newUrl = $this->helper->getUrl("media")."mobikulresized".DS.$this->bannerWidth."x".$this->height.DS.$each->getFilename();
                        $newUrl = $this->helper->getBaseUrl()."pub/media/mobikulresized".DS.$this->bannerWidth."x".$this->height.DS.$each->getFilename();
                    }
                    $oneBanner["url"] = $newUrl;
                    $oneBanner["title"] = $each->getTitle();
                    $oneBanner["bannerType"] = $each->getType();
                    // $oneBanner["dominantColor"] = $this->helper->getDominantColor($newUrl);
                    if ($each->getType() == "category") {
                        $categoryName = $this->categoryResourceModel->getAttributeRawValue($each->getProCatId(), "name", $this->storeId);
                        if (is_array($categoryName)) {
                            continue;
                        }
                        $oneBanner["id"] = $each->getProCatId();
                        $oneBanner["name"] = $categoryName;
                        $oneBanner["url_rewrite"] = $this->getUrlRewrite($this->storeId, \Magento\UrlRewrite\Controller\Adminhtml\Url\Rewrite::ENTITY_TYPE_CATEGORY, $oneBanner["id"]);
                    } elseif ($each->getType() == "product") {
                        $productName = $this->productResourceModel->getAttributeRawValue($each->getProCatId(), "name", $this->storeId);
                        if (is_array($productName)) {
                            continue;
                        }
                        $oneBanner["id"] = $each->getProCatId();
                        $oneBanner["name"] = $productName;
                        $oneBanner["url_rewrite"] = $this->getUrlRewrite($this->storeId, \Magento\UrlRewrite\Controller\Adminhtml\Url\Rewrite::ENTITY_TYPE_PRODUCT, $oneBanner["id"]);
                    }
                    $banners[] = $oneBanner;
                }
                $oneCarousel["banners"] = $banners;
                if (count($oneCarousel["banners"])) {
                    $this->returnArray["carousel"]['image'][] = $oneCarousel;
                }
            }
        }
        return $this->returnArray;
    }


    public function getCategoryUrl($categoryId = null)
    {
        $category = $this->categoryRepository->get($categoryId, 1);
        return $category->getUrl();
    }

    public function getUrlRewrite($storeId=1 , $entityType = "", $id = "" )
    {
        $UrlRewriteCollection=$this->_urlRewrite->getCollection()
        ->addFieldToFilter('entity_type', $entityType)
        ->addFieldToFilter('store_id', $storeId)
        ->addFieldToFilter('entity_id', $id);
        $url = "";
        foreach ($UrlRewriteCollection as $model) {
            $url = $model->getRequestPath();
            break;
        }
        return $url;
    }
}