<?php

namespace Fliegerlogin;

use Fliegerlogin\DbSchema\DbSchema;
use Fliegerlogin\WpAdmin\WpAdmin;
use Fliegerlogin\WpPublic\WpPublic;

class WpVereinsflieger {

	/**
	 * @var WpPublic
	 */
	private $public;
	/**
	 * @var WpAdmin|null
	 */
	private $admin;

	public function __construct(WpPublic $public, ?WpAdmin $admin) {
		$this->public = $public;
		$this->admin = $admin;
	}

	/**
	 * @var WpVereinsflieger|null
	 */
	private static $wpVereinsflieger = null;
	public static function init(): self {
		if (self::$wpVereinsflieger !== null) {
			return self::$wpVereinsflieger;
		}

		// WordPress loads translations for directory-hosted plugins by itself since
		// 4.6, so the explicit call below looks redundant - and Plugin Check flags
		// it. It stays because the filter above lets a club keep its own .mo file
		// from being overwritten by a WordPress.org language pack, and that only
		// works if we take part in loading the textdomain.
		add_filter('load_textdomain_mofile', [self::class, 'preferBundledTextdomain'], 10, 2);
		load_plugin_textdomain('sso-for-vereinsflieger', false, dirname( plugin_basename( FLIEGERLOGIN_BASE_FILE ) ) . '/languages' );

		DbSchema::init();
		Guard::registerGeoDatabaseHooks();

		$public = WpPublic::init();

		$admin = null;
		if (is_admin()) {
			$admin = WpAdmin::init();
		}

		self::$wpVereinsflieger = new self($public, $admin);
		return self::$wpVereinsflieger;
	}

	public static function preferBundledTextdomain(string $mofile, string $domain): string {
		if ($domain !== 'sso-for-vereinsflieger') {
			return $mofile;
		}

		$filename = basename($mofile);
		if (defined('WP_LANG_DIR')) {
			$customFile = WP_LANG_DIR . '/' . 'sso-for-vereinsflieger' . '/' . $filename;
			if (file_exists($customFile)) {
				return $customFile;
			}
		}

		$bundledFile = dirname(FLIEGERLOGIN_BASE_FILE) . '/languages/' . $filename;
		if (file_exists($bundledFile)) {
			return $bundledFile;
		}

		return $mofile;
	}

	public static function activate(): void {
	}

	public static function deactivate(): void {
		Guard::unscheduleGeoDatabase();
	}

	public static function uninstall(): void {
		Guard::uninstallAddOn();
		Options::uninstall();
		DbSchema::uninstall();
	}

}
