<?php
/*
* Singleton slownika
*/

class Dictionary {

	public static $rowSet = array();
	public static $lang;
	public static $allLangs = array();

	public static function Init($lang) {
		if (!in_array($lang, Router::$arrayLang)) {
			throw new LangException('Incorrect language.');
		}

		self::$rowSet = MfDictionaryDAL::GetAllVariables($lang, 0);
		self::$lang = $lang;

		self::$allLangs == array();
		self::$allLangs[$lang] = self::$rowSet;

		$langs = Router::$arrayLang; 
		//$langs = array_filter($langs, create_function('$x', 'return $x != "' . $lang . '";'));		
                $langs = array_filter($langs, function($x) {return $x != "' ".self::$lang.'"';});
		foreach ($langs as $lang) {
			self::$allLangs[$lang] = MfDictionaryDAL::GetAllVariables($lang, 0);
		}
//Utils::ArrayDisplay(self::$allLangs);	
	}

	public static function Translate($keyword) {
		
		self::CheckAndAdd($keyword);

		if($keyword!='' && isset(self::$rowSet[$keyword])) {

			return nl2br(self::$rowSet[$keyword]);
			//Utils::ArrayDisplay(self::$rowSet);
		} else {
			//Utils::ArrayDisplay(self::$rowSet);
			return nl2br($keyword);
		}
	}
	
	public static function CheckAndAdd($keyword) {
		//		$lang = 'pl';
		$lang = Router::$curLang;

		if (!key_exists($keyword, self::$rowSet)) {
			//Utils::ArrayDisplay(self::$rowSet);
			
			$isVariables = MfDictionaryDAL::IsVariables($keyword, $lang);
			if (!$isVariables) {
				
				$arrayLang = Router::GetArrayLang();
				foreach ($arrayLang as $langItem) {
					if ($langItem != 'pl') {
						$replacement = $langItem.'_'.$keyword;
					} else {
						$replacement = $keyword;
					}
					$objDictionary = new MfDictionary(-1);
					$objDictionary->SetId(-1);
					$objDictionary->SetKeyword($keyword);
					$objDictionary->SetReplacement($replacement);
					$objDictionary->SetLang($langItem);
					//Utils::ArrayDisplay($keyword);
					MfDictionaryDAL::Save($objDictionary);
				}

			}
		}
	}
}

?>
