<?php
namespace Bitrix\Main\Localization;

use \Bitrix\Main;
use \Bitrix\Main\IO\Path;

final class Loc
{
	private static $messages = array();
	private static $customMessages = null;
	private static $includedFiles = array();

	/**
	 * Returns translation by message code.
	 * Loc::loadMessages(__FILE__) should be called first once per php file
	 *
	 * @param string $code
	 * @param array|bool $replace e.g. array("#NUM#"=>5)
	 * @param Culture $culture
	 * @return string
	 */
	public static function getMsg($code, $replace = false, Culture $culture = null)
	{
		if($culture == null)
			$culture = \Bitrix\Main\Context::getCurrent()->getCulture();

		$lang = $culture->getLanguage();

		$s = self::$messages[$lang][$code];

		if($replace !== false && is_array($replace))
			foreach($replace as $search => $repl)
				$s = str_replace($search, $repl, $s);

		return $s;
	}

	/**
	 * Load messages from specified language file
	 *
	 * @param string $file
	 * @param Culture $culture
	 * @return array
	 */
	public static function loadMessages($file, Culture $culture = null)
	{
		static $dirCache = array();

		if ($culture == null)
			$culture = \Bitrix\Main\Context::getCurrent()->getCulture();

		$lang = $culture->getLanguage();

		if(!isset(self::$messages[$lang]))
			self::$messages[$lang] = array();

		//first time call only for lang
		if(!isset(self::$customMessages))
			self::$customMessages = self::loadCustomMessages($lang);

		$file = Path::Normalize($file);

		//let's find language folder
		$langDir = $fileName = "";
		$filePath = $file;
		while(($slashPos = strrpos($filePath, "/")) !== false)
		{
			$filePath = substr($filePath, 0, $slashPos);
			if(!isset($dirCache[$filePath]))
				$dirCache[$filePath] = $isDir = is_dir($filePath."/lang");
			else
				$isDir = $dirCache[$filePath];
			if($isDir)
			{
				$langDir = $filePath."/lang";
				$fileName = substr($file, $slashPos);
				break;
			}
		}

		$mess = array();
		if($langDir <> "")
		{
			//load messages for default lang first
			$defaultLang = self::getDefaultLang($lang);
			if($defaultLang <> $lang)
			{
				$langFile = $langDir."/".$defaultLang.$fileName;
				if(file_exists($langFile))
					$mess = self::includeFile($langFile);
			}

			//then load messages for specified lang
			$langFile = $langDir."/".$lang.$fileName;
			if(file_exists($langFile))
				$mess = array_merge($mess, self::includeFile($langFile));

			foreach($mess as $key => $val)
				self::$messages[$lang][$key] = $val;
		}

		return $mess;
	}

	/**
	 * Read messages from user defined lang file
	 */
	private static function loadCustomMessages($lang)
	{
		$customMess = array();
		$root = Main\Server::getRoot();
		if(($fname = Main\Loader::getLocal("php_interface/user_lang/".$lang."/lang.php", $root)) !== false)
		{
			$mess = self::includeFile($fname);

			// typical call is Loc::loadMessages(__FILE__)
			// __FILE__ can differ from path used in the user file
			foreach($mess as $key => $val)
				$customMess[str_replace("\\", "/", realpath($root.$key))] = $val;
		}
		return $customMess;
	}

	/**
	 * Read messages from lang file
	 */
	private static function includeFile($path)
	{
		self::$includedFiles[$path] = $path;

		//the name $MESS is predefined in language files
		$MESS = array();
		include($path);

		//redefine messages from user lang file
		if(!empty(self::$customMessages))
		{
			$path = str_replace("\\", "/", realpath($path));
			if(is_array(self::$customMessages[$path]))
				foreach(self::$customMessages[$path] as $key => $val)
					$MESS[$key] = $val;
		}

		return $MESS;
	}

	/**
	 * Returns default language for specified language. Defualt language is used when translation is not found.
	 *
	 * @param string $lang
	 * @return string
	 */
	public static function getDefaultLang($lang)
	{
		static $subst = array('ua'=>'ru', 'kz'=>'ru', 'ru'=>'ru', 'de'=>'de');
		if(isset($subst[$lang]))
			return $subst[$lang];
		return 'en';
	}

	public static function date($date, Culture $culture = null)
	{
		if ($culture == null)
			$culture = \Bitrix\Main\Context::getCurrent()->getCulture();

		return $date;
	}

	public static function datetime($datetime, Culture $culture = null)
	{
		if ($culture == null)
			$culture = \Bitrix\Main\Context::getCurrent()->getCulture();

		return $datetime;
	}

	public static function money($money, Culture $culture = null)
	{
		if ($culture == null)
			$culture = \Bitrix\Main\Context::getCurrent()->getCulture();

		return $money;
	}
}
