<?php

declare(strict_types=1);

/**
 * @author Amasty Team
 * @copyright Copyright (c) Amasty (https://www.amasty.com)
 * @package Lazy Load for Magento 2 (System)
 */

namespace Amasty\LazyLoad\Observer;

use Amasty\LazyLoad\Model\ConfigProvider;
use Amasty\LazyLoad\Model\Output\LazyConfig\LazyConfig;
use Amasty\LazyLoad\Model\Output\LazyConfig\LazyConfigFactory;
use Amasty\LazyLoad\Model\Output\LazyLoadImageParserProcessor;
use Amasty\LazyLoad\Model\Output\LazyLoadProcessor;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class AjaxLazyLoadProcessor implements ObserverInterface
{
    public function __construct(
        private readonly ConfigProvider $configProvider,
        private readonly LazyConfigFactory $lazyConfigFactory,
        private readonly LazyLoadProcessor $lazyLoadProcessor,
        private ?LazyLoadImageParserProcessor $lazyLoadImageParser = null // TODO move to not optional
    ) {
        $this->lazyLoadImageParser ??= ObjectManager::getInstance()->get(LazyLoadImageParserProcessor::class);
    }

    public function execute(Observer $observer): void
    {
        if (!$this->configProvider->isEnabled()) {
            return;
        }

        /** @var DataObject $data */
        if ($data = $observer->getData('data')) {
            if ($data->hasData('fullLazyConfig')) {
                $lazyConfig = $data->getData('fullLazyConfig');
            } else {
                $params = [];
                if ($data->hasData('pageType')) {
                    $params['pageType'] = $data->getData('pageType');
                }
                $lazyConfig = $this->lazyConfigFactory->create($params);
                if ($data->hasData('lazyConfig')) {
                    $newLazyConfig = array_merge_recursive($lazyConfig->getData(), $data->getData('lazyConfig'));
                    if (isset($newLazyConfig['is_lazy']) && is_array($newLazyConfig['is_lazy'])) {
                        $newLazyConfig['is_lazy'] = end($newLazyConfig['is_lazy']);
                    }

                    $lazyConfig->unsetData()->setData($newLazyConfig);
                }
            }
            $this->lazyLoadProcessor->setLazyConfig($lazyConfig);
            $this->lazyLoadImageParser->setLazyConfig($lazyConfig);
            $page = $data->getData('page');

            if ($lazyConfig->getData(LazyConfig::IS_LAZY)) {
                $this->lazyLoadImageParser->processImages($page);
                $this->lazyLoadProcessor->processLazyImages($page);
                $page .= '<img ' . LazyLoadProcessor::LAZY_LOAD_PLACEHOLDER . ' onload="amlazy();this.remove();"/>';
            }
            $data->setData('page', $page);
        }
    }
}
