package org.kurento.room.ttroomserver;

import static org.kurento.commons.PropertiesManager.getPropertyJson;

import java.util.ArrayList;
import java.util.List;

import org.kurento.commons.ConfigFileManager;
import org.kurento.jsonrpc.JsonUtils;
import org.kurento.room.KurentoRoomServerApp;

import com.google.gson.JsonArray;

public class LocalServerProvider implements ServerProvider {

	//TODO..change the config file name
	private static final String TTROOM_CFG_FILENAME = "kurento-room-demo.conf.json";
	private static final String DEFAULT_SERVER_URIS = "127.0.0.1";
	
	public class LocalServer{
		public LocalServer(){
			sIP = "";
			bUsed = false;
		}
		
		public String sIP;
		public boolean bUsed; 
	}
	
	private List<LocalServer> _serverUris;
	
	static{
		ConfigFileManager.loadConfigFile(TTROOM_CFG_FILENAME);
	}
	
	private void InitServerUrls(){
		JsonArray kmsUris = getPropertyJson(KurentoRoomServerApp.KMSS_URIS_PROPERTY, DEFAULT_SERVER_URIS, JsonArray.class);
		
		List<String> sServers = JsonUtils.toStringList(kmsUris);
		
		for(String sIP : sServers){
			LocalServer server = new LocalServer();
			server.sIP = sIP;
			server.bUsed = false;
			_serverUris.add(server);
		}
	}
	
	public LocalServerProvider(){
		_serverUris = new ArrayList<LocalServer>();
	}

	public String CreateNewServer(){
		
		String sServer = "";
		if(_serverUris.isEmpty()){
			InitServerUrls();
		}
		
		for(LocalServer server : _serverUris){
			if(!server.bUsed){
				sServer = server.sIP;
				server.bUsed = true;
				break;
			}
		}
		
//		int nSize = _serverUris.size();
//		for(int i = 0; i < nSize; i++){
//			LocalServer server = _serverUris.get(i);
//			if(!server.bUsed){
//				sServer = server.sIP;
//				server.bUsed = true;
//				break;
//			}
//		}
		
		return sServer;
	}
	
	public boolean OpenServer(String sServerKey){
		return true;
	}
	
	public String GetServerStatus(String sServerKey){
		String status = "running";
		return status;
	}
	
	public boolean CloseServer(String sServerKey){
		return true;
	}
	
	public boolean DeleteServer(String sServerKey){
		return true;
	}
	
	public String GetExistServer(){
		return CreateNewServer();
	}

	public ErrorCode GetLastError(){
		return ErrorCode.ERROR_NONE;
	}
	
	public String GetServerKey(){
		String skey = "local server";
		return skey;
	}
	
	public String GetServerIP(){
		return null;
	}
	
	public String GetServerName(){
		String sName = "LocalServer";
		return sName;
	}
	
	public void SetUser(String sUser){
		
	}
	
	public void SetPasswd(String sUserPwd){
		
	}
	
	public void SetUrl(String sUrl){
		
	}
	
	public ServerType  GetServerType(){
		return ServerType.TYPE_LOCAL;
	}

}
