<?php

namespace AmadeusAgentur\Stwm_Sitepackage\Service;

use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
use TYPO3\CMS\Core\Package\Event\AfterPackageActivationEvent;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * BrandingService
 */
class BrandingService
{
    
    public function __invoke(AfterPackageActivationEvent $event): void
    {
        if ($event->getPackageKey() === 'stwm_sitepackage') {
            $this->setBackendStyling();
        }
    }
    
    public function setBackendStyling(): void
    {
        if (class_exists(ExtensionConfiguration::class)) {
            $extensionConfiguration = GeneralUtility::makeInstance(
                ExtensionConfiguration::class
            );
            $backendConfiguration = $extensionConfiguration->get('backend');
            
            /** @var array $backendConfiguration */
            
            if (!isset($backendConfiguration['loginLogo']) || trim($backendConfiguration['loginLogo']) === '') {
                $backendConfiguration['loginLogo'] = 'EXT:stwm_sitepackage/Resources/Public/Images/Backend/login-logo.svg';
            }
            
            if (!isset($backendConfiguration['loginBackgroundImage']) || trim($backendConfiguration['loginBackgroundImage']) === '') {
                $backendConfiguration['loginBackgroundImage'] = 'https://source.unsplash.com/collection/915992/1600x900';
            }
            if (!isset($backendConfiguration['loginHighlightColor']) || trim($backendConfiguration['loginHighlightColor']) === '') {
                $backendConfiguration['loginHighlightColor'] = '#009999';
            }
            
            if (!isset($backendConfiguration['loginFootnote']) || trim($backendConfiguration['loginFootnote']) === '') {
                $backendConfiguration['loginFootnote'] = 'wwwwww.amadeus-agentur.com';
            }
            
            // Workaround for
            // https://review.typo3.org/c/Packages/TYPO3.CMS/+/62650
            $reflection = new \ReflectionClass(ExtensionConfiguration::class);
            $parameters = $reflection->getMethod('set')->getParameters();
            if (count($parameters) === 3) {
                /** @phpstan-ignore-next-line */
                $extensionConfiguration->set('backend', '', $backendConfiguration);
            } else {
                /** @phpstan-ignore-next-line */
                $extensionConfiguration->set('backend', $backendConfiguration);
            }
        }
    }
}
