<?php

class Languages {
	
	static private $instance=null;

	public static function getInstance(){
		if(self::$instance==null) self::$instance = new Languages();
		return self::$instance;
	}	 	

	function __constructor(){}

	//public to all
	function getDefaultLanguage(){
	 	$this->getLanguage((object) array("language" => "__default"), true, true);
	}

	function deleteLanguage($d){
	 
		if(!Util::deleteFile("resources/languages/".basename($d->language).".txt"))
			Response::sendResponse(false, null, "auth", "cannot_delete");
			
		$retObj = (object) array();
		$retObj->success = true;
		
		Response::sendOKResponse($retObj);
		
	}


	function getLanguage($d, $output=true, $formated=false){
 	 
 	 	if($d->language=="__default"){
			$langFile = "resources/languages/".basename($d->language).".xml";
		}else{
			$langFile = "resources/languages/".basename($d->language).".txt";
		}
		
 	 	if(!is_file($langFile) && $output==true){
 	 		Response::sendResponse(false, null, "language", "doesnot_exist");
		}
			//print_R(Util::readXmlFile($langFile));
		if($d->language=="__default"){
			$lang = WddxSerializer::deserialize(Util::readXmlFile($langFile));
		}else{
		 	$lang = DataSerializer::deserialize(Util::readFile($langFile));
		}
		 
 	 	//print_R(	$lang);
 	 	if($formated==true){
 	 		$langObj = (object) array(); 	
 	 		for($i=0; $i<count($lang); $i++){
 	 			$n = $lang[$i]->name;
 	 			$langObj->$n = $lang[$i]->value;
 	 		}
 	 		$lang = $langObj;
 	 	}
 	 	
		  
		$retObj = (object) array(); 
 	 	if(!empty($d->language2)){
 	 		$langFile2 = "resources/languages/".basename($d->language2).".txt";
 	 		if(is_file($langFile2)){
 	 		 $retObj->language2 = DataSerializer::deserialize(Util::readFile($langFile2));
 	 		}
 	 	}
 	 	
 	 	$retObj->language = $lang;
 	 	
 	 	if($output)
	 		Response::sendOKResponse($retObj);
	 	else
	 		return $lang;
		
	}
	function saveLanguage($d){
	 	  
 	 //	print_r($d);
		$langFile = "resources/languages/".basename($d->language).".txt";
 	 	if(!Util::writeFile($langFile, DataSerializer::serialize($d->languageData))){
 	 		Response::sendResponse(false, null, "language", "cannot_write");
		}

		$lang = DataSerializer::deserialize(Util::readFile($langFile));
 	 	
		Response::sendOKResponse($lang);
	}

	function changeLanguage($d){
		
		$userFile = Config::get("private_system_accounts_path")."/".User::GetInstance()->userInfo->username.".txt";
	 	$userXmlStr = Util::readFile($userFile);
		$userObj = DataSerializer::deserialize($userXmlStr);
	 	$userObj->language = $d->language;
	 	
	 	$retObj = (object) array();
	 	$retObj->success = Util::writeFile($userFile, DataSerializer::serialize($userObj));
	 	Response::sendOKResponse($retObj);
	 	
	}

	function loadLanguages(){

	 	$ud = new UD();
	 	$FaF = $ud->getFoldersAndFiles("resources/languages");
	 	if($FaF<0){
	 		Response::sendErrorResponse($ud->getErrorID($FaF), $ud->getErrorMsg($FaF));
		}
		Response::sendOKResponse($FaF);
	
	}
}

?>