<?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\Model\LazyScript;

use Magento\Framework\App\ObjectManager;
use Magento\Framework\View\Helper\SecureHtmlRenderer;

class Lozad implements LazyScriptInterface
{
    /**
     * @var SecureHtmlRenderer
     */
    private $secureRenderer;

    public function __construct(
        ?SecureHtmlRenderer $secureRenderer = null // TODO move to not optional
    ) {
        $this->secureRenderer = $secureRenderer ?? ObjectManager::getInstance()->get(SecureHtmlRenderer::class);
    }

    public function getName(): string
    {
        return (string)__('Lozad Lazy Script');
    }

    public function getType(): string
    {
        return 'lozad';
    }

    public function getCode(): string
    {
        $script = <<<SCRIPT
            window.amlazycallback = function () {
                if (typeof window.amLozadInstance !== "undefined") {
                    window.amLozadInstance.observe();
                }
            };
            require(["Amasty_LazyLoad/js/lozad"], function(lozad) {
                const selectors = "img[data-amsrc], img[data-amsrcset], source[data-amsrcset], picture",
                      options = {};
                window.amLozadInstance = lozad(selectors, options);
                window.amLozadInstance.observe();
            });
        SCRIPT;

        return $this->secureRenderer->renderTag(
            'script',
            [],
            $script,
            false
        );
    }

    public function getSupportedTags(): array
    {
        return ['img', 'source'];
    }
}
