<?php

namespace Leadlion\Autogedal\Observer;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Catalog\Model\ResourceModel\Product as ProductResourceModel;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\App\State;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Message\ManagerInterface;
use Magento\Indexer\Model\Indexer\State as IndexerState;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Catalog\Model\Product\Action;

class AddGoogleCategory implements ObserverInterface
{
    const XML_GOOGLE_FEED_PATH = 'leadlion/google_feed/product_type';
    const GOOGLE_DESC = 'google_descrip';

    /**
     * @var Action
     */
    private $productAction;

    /**
     * @var ManagerInterface
     */
    protected $messageManager;

    /**
     * @var State
     */
    protected $state;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepository;

    /**
     * @var CollectionFactory
     */
    protected $productCollectionFactory;

    /**
     * @var ProductResourceModel
     */
    protected $productResourceModel;
    private $scopeConfig;
    private $serializer;

    public function __construct(
        ManagerInterface $messageManager,
        State $state,
        LoggerInterface $logger,
        ProductRepositoryInterface $productRepository,
        CollectionFactory $productCollectionFactory,
        ProductResourceModel $productResourceModel,
        ScopeConfigInterface $scopeConfig,
        SerializerInterface $serializer,
        Action $productAction
    ) {
        $this->messageManager = $messageManager;
        $this->state = $state;
        $this->logger = $logger;
        $this->productRepository = $productRepository;
        $this->productCollectionFactory = $productCollectionFactory;
        $this->productResourceModel = $productResourceModel;
        $this->scopeConfig = $scopeConfig;
        $this->serializer = $serializer;
        $this->productAction = $productAction;
    }

    /**
     * @param Observer $observer
     */
    public function execute(Observer $observer)
    {
        try {
            $areaCode = $this->state->getAreaCode();
        } catch (LocalizedException $exception) {
            $areaCode = null;
        }

        try {
            $product = $observer->getProduct();
        } catch (\Throwable $exception) {
            $this->logger->critical($exception);

            return;
        }

        if (!$product || empty($product)) {
            return;
        }

        if (!$product->getGoogleDescrip()) {
            try {
                $feedConfig = $this->getGoogleFeedConfig();
                $categoriesIds = $product->getCategoryIds();
                if (!empty($categoriesIds)) {
                    $googleCategoryDesc = $product->getName();
                    foreach ($categoriesIds as $key => $categoryId) {
                        if (isset($feedConfig[$categoryId])) {
                            $attrCodesArray = explode(',', $feedConfig[$categoryId]);
                            foreach ($attrCodesArray as $attrCode) {
                                $value = $product->getAttributeText($attrCode);
                                if ($value) {
                                    $googleCategoryDesc .= ', '.$value;
                                }
                            }
                        }
                    }
                    $this->productAction->updateAttributes(
                        [$product->getEntityId()],
                        [self::GOOGLE_DESC => $googleCategoryDesc],
                        0
                    );
                }
            } catch (\Throwable $exception) {
                if ($areaCode === 'adminhtml') {
                    $this->messageManager->addErrorMessage($exception->getMessage() . ' ' . __('The google description could not be saved.'));
                } else {
                    $this->logger->critical($exception);
                }
            }
        }
    }

    private function getGoogleFeedConfig()
    {
        $confSettings = $this->scopeConfig->getValue(
            self::XML_GOOGLE_FEED_PATH,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
        $info = [];
        if ($confSettings) {
            $feedConfig = $this->serializer->unserialize($confSettings);

            $info = [];
            foreach ($feedConfig as $config) {
                $info[$config['category_id']] = $config['attributes_code'];
            }
        }
        
        return $info;
    }
}
