package com.lordcard.network.cmdmgr;

import android.text.TextUtils;

import com.lordcard.constant.Database;
import com.lordcard.network.http.HttpRequest;
import com.lordcard.network.socket.ICallback;

public class ClientCmdMgr {

	private static long seq = 1; //娑堟伅搴忓垪鍙? 涓€鐩撮€掑

	private static Client client = null;

	/**
	 * 寤虹珛杩炴帴
	 * @Title: start  
	 * @param @param ip
	 * @param @param port
	 * @return void
	 * @throws
	 */
	public static boolean startClient(ICallback callback) {
		try {
//			HttpSynch.synchGameServer();
			HttpRequest.getCacheServer(true);
			
			String server = Database.GAME_SERVER;
			if (TextUtils.isEmpty(server))
				return false;

			String[] ipPort = server.split(":");
			if (ipPort.length != 2)
				return false;

			String ip = ipPort[0];
			int port = Integer.parseInt(ipPort[1]);

			boolean isNewClient = false;
			if (client == null) {
				isNewClient = true;
			} else if (client != null && !client.isConnected()) {
				client.destory();
				isNewClient = true;
			}

			if (isNewClient) {
				client = new Client(ip, port);
			}
			if (client.isConnected()) {
				client.setCallback(callback);
				client.startGame();
				return true;
			}
		} catch (Exception e) {
			closeClient();
		}
		return false;
	}

	/**
	 * Client 缁撴潫(閫€鍑烘父鎴忕晫闈?
	 * @Title: destory  
	 * @param 
	 * @return void
	 * @throws
	 */
	public static void closeClient() {
		if (client != null) {
			client.destory();
		}
		client = null;
	}

	/**
	 * 璁剧疆Client鐘舵€?
	 * @Title: setClientStatus  
	 * @param 
	 * @return void
	 * @throws
	 */
	public static void setClientStatus(int status) {
		if (client != null) {
			client.setStatus(status);
		}
	}

	/**
	 * 閲嶈繛娆℃暟褰掗浂
	 * @Title: resetRelinkCount  
	 * @param 
	 * @return void
	 * @throws
	 */
	public static void resetRelinkCount() {
		client.setRelinkCount(0);
	}

	/**
	 * 鍙戦€佹秷鎭?
	 * @Title: sendCmd  
	 * @param @param detail
	 * @return void
	 * @throws
	 */
	public static void sendCmd(CmdDetail detail) {
		if (client != null) {
			client.sendCmd(detail);
		}
	}

	/**
	 * 涓€灞€缁撴潫
	 * @Title: gameOver  
	 * @param 
	 * @return void
	 * @throws
	 */
	public static void gameOver() {
		if (client != null) {
			client.gameOver();
		}
	}

	public synchronized static long getCmdSeq() {
		return seq++;
	}
}