<?php

declare(strict_types=1);

namespace OCA\RePod\AppInfo;

use OCP\App\AppPathNotFoundException;
use OCP\App\IAppManager;
use OCP\AppFramework\App;
use OCP\AppFramework\Bootstrap\IBootContext;
use OCP\AppFramework\Bootstrap\IBootstrap;
use OCP\AppFramework\Bootstrap\IRegistrationContext;
use OCP\Server;
use OCP\Util;

class Application extends App implements IBootstrap
{
	public const APP_ID = 'repod';
	private const GPODDERSYNC_ID = 'gpoddersync';
	private const GPODDERSYNC_MIN_VERSION = '3.8.1';

	public function __construct() {
		parent::__construct(self::APP_ID);
	}

	public function boot(IBootContext $context): void {
		/** @psalm-suppress DeprecatedInterface */
		$appContainer = $context->getAppContainer();

		/** @var IAppManager $appManager */
		$appManager = $appContainer->get(IAppManager::class);

		$gpoddersync = $appManager->isEnabledForUser(self::GPODDERSYNC_ID);
		if (!$gpoddersync) {
			try {
				$appManager->enableApp(self::GPODDERSYNC_ID);
			} catch (AppPathNotFoundException $e) {
			}
		}

		/** @psalm-suppress DeprecatedMethod */
		Util::connectHook('\OCP\Config', 'js', $this, 'extendJsConfig');
	}

	public function register(IRegistrationContext $context): void {}

	public static function extendJsConfig(array $settings): void {
		/** @var IAppManager $appManager */
		$appManager = Server::get(IAppManager::class);

		if (is_array($settings['array']) && array_key_exists('oc_appconfig', $settings['array'])) {
			/** @var array $appConfig */
			$appConfig = json_decode((string) $settings['array']['oc_appconfig'], true);
			$appConfig['repod'] = [
				'gpodder' => $appManager->isEnabledForUser(self::GPODDERSYNC_ID)
					&& version_compare($appManager->getAppVersion(self::GPODDERSYNC_ID), self::GPODDERSYNC_MIN_VERSION) >= 0,
			];
			$settings['array']['oc_appconfig'] = json_encode($appConfig);
		}
	}
}