<?php
class Language_Switcher {
	/**
	 * @var Language_Switcher
	 */
	private static $instance;

	/**
	 * The array containing all the mofiles
	 *
	 * @var array
	 */
	private $mo_files;

	protected function __construct() {

		/**
		 * Store all the textdomain and files
		 */
		add_filter( 'load_textdomain_mofile', array( $this, 'load_textdomain_mofile' ), 1, 2 );
	}

	/**
	 * @return self
	 * @author Nicolas Juen
	 */
	public static function get_instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Add the mo file to the class
	 *
	 * @param string $mo_file : the mo file path
	 * @param string $domain : domain
	 *
	 * @author Nicolas Juen
	 * @return string
	 */
	public function load_textdomain_mofile( $mo_file, $domain ) {
		$this->mo_files[ $domain ][] = $mo_file;
		return $mo_file;
	}

	/**
	 * Unload all registered files
	 *
	 * @author Nicolas Juen
	 */
	private function unload_text_domains() {
		// Unload the files
		foreach ( $this->mo_files as $domain => $file ) {
			unload_textdomain( $domain );
		}

		unload_textdomain( 'default' );
	}

	/**
	 * Load other locale files
	 *
	 * @param $locale_to : the locale to switch
	 *
	 * @author Nicolas Juen
	 * @return bool
	 */
	public function switch_locale( $locale_to ) {
		global $locale;

		/**
		 * Do not switch locale if same
		 * or empty mo files
		 */
		if ( $locale === $locale_to || empty( $this->mo_files ) ) {
			return false;
		}

		remove_filter( 'load_textdomain_mofile', array( $this, 'load_textdomain_mofile' ), 1, 2 );
		$this->unload_text_domains();

		// Reload the files
		foreach ( $this->mo_files as $domain => $files ) {
			foreach ( $files as $file ) {
				load_textdomain( $domain, str_replace( $locale, $locale_to, $file ) );
			}
		}

		// Load WP text domain
		load_default_textdomain( $locale_to );

		return true;
	}

	/**
	 * Restore the original locale
	 *
	 * @author Nicolas Juen
	 */
	public function restore_locale() {
		$this->unload_text_domains();
		$this->switch_locale( get_locale() );
	}
}