<?php
/**
 * Translator utility class.
 *
 * @package Ealab\Deployer
 */

namespace Ealab\Deployer\Utility;

use Dakwamine\Component\ComponentBasedObject;
use PhpMyAdmin\MoTranslator\Loader;

/**
 * Translator utility class.
 */
class Translator extends ComponentBasedObject {
	/**
	 * The detected default locale.
	 *
	 * @var string|null
	 */
	private static ?string $detected_default_locale = null;

	/**
	 * Gets the default locale.
	 *
	 * @return string The default locale.
	 */
	private static function getDefaultLocale(): string {
		if ( null === static::$detected_default_locale ) {
			if ( function_exists( 'get_locale' ) ) {
				// WordPress implementation.
				static::$detected_default_locale = get_locale();
			} else {
				// Fallback to the translator implementation.
				static::$detected_default_locale = Loader::getInstance()->detectlocale();
			}
		}

		return static::$detected_default_locale;
	}

	/**
	 * Gets the default domain.
	 *
	 * @return string The default domain.
	 */
	private static function getDefaultDomain(): string {
		return 'deployer-core';
	}

	/**
	 * Prepares the translator.
	 *
	 * This method should be called as soon as possible in the application.
	 */
	public static function prepare(): void {
		// Load the gettext translation functions.
		Loader::loadFunctions();

		$loader = Loader::getInstance();

		// Set the default locale.
		$loader->setlocale( static::getDefaultLocale() );

		// Set the default text domain.
		$loader->textdomain( static::getDefaultDomain() );

		// Domain to path mapping.
		// For reference, a path to the .mo files is like:
		// /path/to/wordpress/wp-content/plugins/deploy-sync-content/src/_locale/<lang_LANG>/<CATEGORY>/<DOMAIN>.mo
		// where:
		// - <lang_LANG> is the language code, e.g. "fr_FR", "fr".
		// - <CATEGORY> is usually "LC_MESSAGES" (gettext category).
		// - <DOMAIN> is the domain name, e.g. "deployer-core". "deployer-core" is the only domain used in this plugin.
		$mappings = array(
			'deployer-core' => __DIR__ . '/../_locale',
		);

		foreach ( $mappings as $domain_name => $path ) {
			$loader->bindtextdomain( $domain_name, $path );
		}
	}
}
