package org.kurento.room.ttroomserver;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class AliServerProvider implements ServerProvider {

	private String _sUser;
	private String _sPwd;
	private String _sUrl;
	private ErrorCode _ErrCode;
	
	private String _sInstanceID;
	private String _sServerIP;
	private String _sServerName;

	public void SetUser(String sUser){
		_sUser = sUser;
	}
	
	public void SetPasswd(String sUserPwd){
		_sPwd = sUserPwd;
	}
	
	public void SetUrl(String sUrl){
		_sUrl = sUrl;
	}
	
	/*
	 * in order to determine kurento-media-server open or not 
	 */
	private static boolean isHostConnectable(String host, int port) {
        Socket socket = new Socket();
        try {
            socket.connect(new InetSocketAddress(host, port));
        } catch (IOException e) {
            //e.printStackTrace();
        	System.out.println("kurento-media-server未启动!");
            return false;
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                //e.printStackTrace();
            	System.out.println("kurento-media-server未启动!");
            }
        }
        return true;
    }

	public String CreateNewServer(){
		String sResult = "";
		
		String sRequest = _sUrl + "createAndStart.do";
		sResult = HttpTool.sendGet(sRequest , "");
		
		//TODO. process error message
		
		//analysis the response : get the instanceId and server ip
		JsonParser parser = new JsonParser();
		JsonElement jsonEl = parser.parse(sResult);
		JsonObject jsObj = null; 
		jsObj = jsonEl.getAsJsonObject();
		
		//TODO ... should process the return message in pre call
		_sInstanceID = jsObj.get("instanceId").getAsString();
		_sServerIP = jsObj.get("ipDress").getAsString();
		_sServerName = jsObj.get("hostname").getAsString();
		
		return sResult;
	}
	
	public boolean OpenServer(String sServerKey){
		String sRequest = _sUrl + "start.do";
		String sParam = "instanceId=" + sServerKey;
		String sResult = HttpTool.sendGet(sRequest , sParam);
		
		//TODO. process the start command response
		/*JsonParser parser = new JsonParser();
		JsonElement jsonEl = parser.parse(sResult);
		JsonObject jsObj = null; 
		jsObj = jsonEl.getAsJsonObject();
		String sTmp = jsObj.get("").getAsString();
		*/
		
		sRequest = _sUrl + "describe.do";
		sParam = "instanceId=" + sServerKey;
		
		 int nCount = 0;
		 
		  do{
			  sResult = HttpTool.sendGet(sRequest , sParam);
			  if(sResult.toLowerCase().equals("running")){
				  break;
			  }
			  
			  nCount++;
			  
			  //in case its freeze
			  if(nCount > 60){
				  break;
			  }
			  
	          try { 
	              Thread.sleep(1000); 
	          } catch (InterruptedException e) { 
	              //e.printStackTrace();
	        	  System.out.println("sleep未达到设定时间!");
	          } 
			  
		  }while( true );
		  
		  boolean bKmsOpen = false;
		  int nMaxRetryTimes = 20;
		  int nTimes = 0;
		  do{
			  nTimes++;
			  bKmsOpen = isHostConnectable(_sServerIP , 8888);

			  try { 
	              Thread.sleep(5000); 
	          } catch (InterruptedException e) {
	        	  
	          }
			  
			  if(nTimes > nMaxRetryTimes){
				  break;
			  }
			  
		  }while(!bKmsOpen);
		  
		return true;
	}
	
	public String GetServerStatus(String sServerKey){
		String sRequest = _sUrl + "describe.do";
		String sParam = "instanceId=" + sServerKey;
		String sResponse = HttpTool.sendGet(sRequest , sParam);
		
		//TODO...process error message

		return sResponse;
	}
	
	public boolean CloseServer(String sServerKey){
		String sRequest = _sUrl + "stop.do";
		String sParam = "instanceId=" + sServerKey;
		String sResponse = HttpTool.sendGet(sRequest , sParam);

		//TODO...process error message

		return true;
	}
	
	public boolean DeleteServer(String sServerKey){
		
		//TODO..first should query the server status only status==stopped can delete the server 
		String sRequest = _sUrl + "describe.do";
		String sParam = "instanceId=" + sServerKey;
		String sResponse = HttpTool.sendGet(sRequest , sParam);
		System.out.print(sResponse + "\r\n");
		if(!sResponse.toLowerCase().equals("stopped")){
			return false;
		 }
		
		sRequest = _sUrl + "delete.do";
		sResponse = HttpTool.sendGet( sRequest , sParam );
		
		//TODO...process error message
		
		return true;
	}
	
	public String GetExistServer(){
		String sRequest = _sUrl + "GetExistInstance.do";
		String sResponse = HttpTool.sendPost(sRequest, "");
		
		//TODO. process the error message		
		JsonParser parser = new JsonParser();
		JsonElement jsonEl = parser.parse(sResponse);
		JsonObject jsObj = null; 
		jsObj = jsonEl.getAsJsonObject();
		
		_sInstanceID = jsObj.get("instanceId").getAsString();
		_sServerIP = jsObj.get("ipDress").getAsString();
		
		return sResponse;
	}
	
	public ErrorCode GetLastError(){
		
		return ErrorCode.ERROR_NONE;
	}
	
	public String GetServerKey(){
		return _sInstanceID;
	}
	
	public String GetServerIP(){
		return _sServerIP;
	}
	
	public String GetServerName(){
		return _sServerName;
	}
	
	public ServerType  GetServerType(){
		return ServerType.TYPE_REMOTE;
	}

}
