<?php

declare(strict_types=1);

namespace FiloBlu\Refilo\Remote\Entity;

use FiloBlu\Refilo\Helper\Catalog\CategoryHelper;
use Magento\Catalog\Api\Data\CategoryInterface;
use Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\UrlRewrite\Service\V1\Data\UrlRewrite;

/**
 * Class MagentoToRefiloCategoryAdapter
 * @package FiloBlu\Refilo\Remote\Entity
 */
class MagentoToRefiloCategoryAdapter
{
    /**
     * @var array
     */
    protected $categoryUrlSuffix = [];

    /**
     * @var ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @var CategoryHelper
     */
    private $categoryHelper;

    /**
     * MagentoToRefiloCategoryAdapter constructor.
     * @param CategoryHelper $categoryHelper
     * @param ScopeConfigInterface $scopeConfig
     */
    public function __construct(
        CategoryHelper $categoryHelper,
        ScopeConfigInterface $scopeConfig
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->categoryHelper = $categoryHelper;
    }

    /**
     * @param CategoryInterface|\Magento\Catalog\Model\Category $magentoCategory
     * @param Category $refiloCategory
     * @return Category
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function adapt(CategoryInterface $magentoCategory, Category $refiloCategory): Category
    {
        $image = ($magentoCategory->getData('image')) ? str_replace(
            '/media/',
            '',
            $magentoCategory->getData('image')
        ) : null;
        $mobileImage = ($magentoCategory->getData('mobile_image')) ? str_replace(
            '/media/',
            '',
            $magentoCategory->getData('mobile_image')
        ) : null;
        $attributes = $magentoCategory->getAttributes();
        // @TODO Every meta value is retrieved from Mageworx, please get rid of this module asap
        $refiloCategory
            ->setId($magentoCategory->getId())
            ->setEnabled($magentoCategory->getIsActive() ? '1' : '0')
            ->setParentId($magentoCategory->getParentId())
            ->setPosition($magentoCategory->getPosition())
            ->setCreatedAt($magentoCategory->getCreatedAt())
            ->setUpdatedAt($magentoCategory->getUpdatedAt())
            ->setPath($this->getUrlPath($magentoCategory))
            ->setPosition((int)$magentoCategory->getPosition())
            ->setLevel($magentoCategory->getLevel())
            ->setChildrenCount((int)$magentoCategory->getChildrenCount())
            ->setName($magentoCategory->getName())
            ->setDescription($this->categoryHelper->parseDescription($magentoCategory->getDescription()))
            ->setMetaTitle($magentoCategory->getMetaTitle())
            ->setMetaKeywords($magentoCategory->getMetaKeywords())
            ->setMetaDescription($magentoCategory->getMetaDescription())
            ->setMetaRobots($magentoCategory->getMetaRobots())
            ->setCategorySeoName($magentoCategory->getCategorySeoName())
            ->setIncludeInMenu($magentoCategory->getIncludeInMenu())
            ->setExcludeFromSearch((int)$magentoCategory->getRefiloExcludeFromSearch())
            ->setRefiloTemplate($magentoCategory->getRefiloTemplate())
            ->setFullName($this->categoryHelper->getFullName($magentoCategory))
            ->setIsAnchor((int)$magentoCategory->getIsAnchor())
            ->setImage($image)
            ->setMobileImage($mobileImage)
            ->setChildren($this->categoryHelper->getChildren($magentoCategory))
            ->setAllChildren($this->categoryHelper->getChildren($magentoCategory, true))
            ->setTileVariant($magentoCategory->getRefiloTileVariant())
            ->setHideFilters((bool)$magentoCategory->getRefiloHideFilters())
            ->setHideSortby((bool)$magentoCategory->getRefiloHideSortby())
            ->setHeadingVariant($magentoCategory->getRefiloHeadingVariant() ?? null)
            ->setCategoryIdentifier($magentoCategory->getRefiloCategoryIdentifier() ?? null)
            ->setRefiloViewModeEnabled((bool)$magentoCategory->getRefiloViewModeEnabled())
            ->setRefiloViewMode($magentoCategory->getRefiloViewMode() ?? null)
            ->setRefiloSiblingsCategoriesEnabled((bool)$magentoCategory->getRefiloSiblingsCategoriesEnabled())
            ->setRefiloChildrenCategoriesEnabled((bool)$magentoCategory->getRefiloChildrenCategoriesEnabled())
            ->setEmotionalProducts($this->categoryHelper->getRefiloEmotionalProducts($magentoCategory));

        if (isset($attributes['refilo_children_categories_enabled']) && $magentoCategory->getRefiloChildrenCategoriesEnabled() === null) {
            $refiloCategory->setRefiloChildrenCategoriesEnabled(
                (bool)$attributes['refilo_children_categories_enabled']->getDefaultValue()
            );
        }

        if (isset($attributes['refilo_siblings_categories_enabled']) && $magentoCategory->getRefiloSiblingsCategoriesEnabled() === null) {
            $refiloCategory->setRefiloSiblingsCategoriesEnabled(
            (bool)$attributes['refilo_siblings_categories_enabled']->getDefaultValue()
            );
        }

        if (!$this->scopeConfig->isSetFlag('catalog/magento_catalogpermissions/enabled')) {
            $refiloCategory->setPermissions([]);
        }

        return $refiloCategory;
    }

    /**
     * @param CategoryInterface $category
     * @return string
     */
    public function getUrlPath(CategoryInterface $category)
    {
        $storeId = $category->getStoreId();

        if (!isset($this->categoryUrlSuffix[$storeId])) {
            $this->categoryUrlSuffix[$storeId] = $this->scopeConfig->getValue(
                CategoryUrlPathGenerator::XML_PATH_CATEGORY_URL_SUFFIX,
                ScopeInterface::SCOPE_STORE,
                $storeId
            );
        }

        return '/' . $category->getData(UrlRewrite::REQUEST_PATH); //. $this->categoryUrlSuffix[$storeId];
    }

}
