<?php
namespace JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Helpers;
/** 
 * @package JREALTIMEANALYTICS::FRAMEWORK::administrator::components::com_jrealtimeanalytics
 * @subpackage framework
 * @subpackage helpers
 * @author Joomla! Extensions Store
 * @copyright (C) 2013 - Joomla! Extensions Store
 * @license GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html   
 */
defined('_JEXEC') or die('Restricted access');
use Joomla\CMS\Language\Text;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Language as CMSLanguage;
use Joomla\CMS\Language\LanguageHelper;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Helpers\Language as JRealtimeHelpersLanguage;

/**
 * Manage language inject translations for frontend client JS App
 * 
 * @package JREALTIMEANALYTICS::FRAMEWORK::administrator::components::com_jrealtimeanalytics
 * @subpackage framework
 * @subpackage helpers
 * @since 2.0
 */ 
class Language extends CMSLanguage {
	/**
	 * Injector language const to JS domain with same name mapping
	 * @access protected
	 * @param $translations array
	 * @param $document Object&
	 * @return void
	 */
	public function injectJsTranslations(&$translations, &$document) {
		$jsInject = null;
 		// Do translations
		foreach ( $translations as $translation ) {
			$jsTranslation = strtoupper ( $translation );
			$translated = Text::_( $jsTranslation, true );
			$jsInject .= <<<JS
				var $translation = '{$translated}'; 
JS;
		}
		$document->getWebAssetManager()->addInlineScript($jsInject);
	}

	/**
	 * Get the sef string for the current language
	 *
	 * @access public
	 * @return string
	 */
	public static function getCurrentSefLanguage() {
		static $defaultLanguageSef;
		if($defaultLanguageSef) {
			return $defaultLanguageSef;
		}
		
		$knownLangs = LanguageHelper::getLanguages();
			
		// Setup predefined site language
		$defaultLanguageCode = Factory::getApplication()->getLanguage()->getTag();
	
		foreach ($knownLangs as $knownLang) {
			if($knownLang->lang_code == $defaultLanguageCode) {
				$defaultLanguageSef = $knownLang->sef;
				break;
			}
		}
	
		return $defaultLanguageSef;
	}
	
	/**
	 * Override Language instantiator 
	 * 
	 * @access	public
	 * @since	1.5
	 */
	public static function getInstance($lang = null, $debug = false) {
		static $lang;
		
		if(!is_object($lang)) {
			$conf	= Factory::getApplication()->getConfig();
			$locale	= $conf->get('config.language');
			$lang = new JRealtimeHelpersLanguage($locale);
			$lang->setDebug($conf->get('config.debug_lang'));
		}
		
		return $lang;
	}
}
