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

import com.taurus.core.entity.ITArray;
import com.taurus.core.entity.ITObject;
import com.taurus.core.entity.TArray;
import com.taurus.core.entity.TObject;
import com.taurus.core.events.Event;
import com.taurus.core.events.IEventListener;
import com.taurus.core.plugin.PluginService;
import com.taurus.core.util.ICallback;
import com.taurus.core.util.StringUtil;

import taurus.client.Message;
import taurus.client.MessageResponse;
import taurus.client.NetManager;
import taurus.client.SocketCode;
import taurus.client.TaurusClient;
import taurus.client.TaurusClient.ConnectionProtocol;
import taurus.client.TaurusClient.NetClientEvent;
import taurus.client.business.AccountBusiness;
import taurus.client.business.GroupRoomBusiness;

public class Test2 {
	// 玩家手牌
	public static List<Integer> cardInhand = new ArrayList<Integer>();
	public static int seat = 0;
	public static int playerId = 219916;
	public static String password = "123456";
	public static String session = "";
	public static String token = "";
	public static TaurusClient client = null;

	static final void tcp_test() throws Exception {
		ITObject validate = TObject.newInstance();
		AccountBusiness accountBusiness = new AccountBusiness();
		// 登录获取session跟token
		ITObject object = accountBusiness.idPasswordLogin(playerId, password);
		validate.putString("token", object.getString("token"));
		token = object.getString("token");
		session = accountBusiness.getSession();
		System.out.println(session + "," + object.getString("token"));
		// group进入房间
		ITObject roomInfo = GroupRoomBusiness.joinRoom(495612, "864687", session, null);

		client = new TaurusClient("101.35.26.131:8893", "game", ConnectionProtocol.Tcp);
//		final TaurusClient client = new TaurusClient("192.168.1.2:8097", "game", ConnectionProtocol.Tcp);

		client.connect();
		client.addEventListener(NetClientEvent.OnEvent, new IEventListener() {
			@Override
			public void handleEvent(Event event) {
				// 获取 msg 对象
				Message message = (Message) event.getParameter("msg");
				if (message == null)
					return;
				// 获取 param（ITObject）
				ITObject param = message.param;
				if (param == null)
					return;
				// 先判断协议号，取不同的参数
				String command = message.command;
				if (StringUtil.isNotEmpty(command)) {
					if ("812".equalsIgnoreCase(command)) {
						sleepTime(1000);
						drawCard(command, message);
					} else if ("820".equalsIgnoreCase(command)) {
						changePlayer(command, message);
					} else if ("819".equalsIgnoreCase(command)) {
						getCard(command, message);
					} else if ("811".equalsIgnoreCase(command)) {
						cardInHead(command, message);

					} else if ("813".equalsIgnoreCase(command)) {
						sleepTime(2000);
						outCard(command, message);

					} else if ("817".equalsIgnoreCase(command)) {
						ready();
					} else if ("814".equalsIgnoreCase(command)) {
						sleepTime(2000);
						actionCard(command, message);

					}
				}

				// 处理出牌逻辑
				System.out.println("event-----------" + event);
			}
		});
		client.addEventListener(NetClientEvent.Connect, new IEventListener() {
			@Override
			public void handleEvent(Event event) {
				SocketCode code = (SocketCode) event.getParameter("code");
				if (code == SocketCode.Connect) {
					System.out.println("连接成功");

				} else {
					System.out.println("连接失败");

				}
			}
		});
		ITObject params = TObject.newInstance();
		params.putString("session", session + "," + object.getString("token"));

		joinRoom();
		ready();
	}

	/**
	 * 出牌协议 812
	 * 
	 * @param command
	 * @param message
	 * @return
	 */
	public static String drawCard(String command, Message message) {
		if (command.equalsIgnoreCase("812")) {
			ITObject param = message.param;
			if (param == null)
				return null;

			System.out.println("座位号:" + param.getInt("seat") + "的用户出牌:" + param.getInt("card"));

		}
		return null;
	}

	/**
	 * 位置转换协议 820
	 * 
	 * @param command
	 * @param message
	 * @return
	 */
	public static String changePlayer(String command, Message message) {
		if (command.equalsIgnoreCase("820")) {
			ITObject param = message.param;
			if (param == null)
				return null;

			System.out.println("出牌权转移到座位号:" + param.getInt("seat") + "的用户");
//			{seat=2}

		}
		return null;
	}

	/**
	 * 摸牌协议 819
	 * 
	 * @param command
	 * @param message
	 * @return
	 */
	public static String getCard(String command, Message message) {
		if (command.equalsIgnoreCase("819")) {
			ITObject param = message.param;
			if (param == null)
				return null;
//            {seat=2, Ishupai=0, isBaoTing=-1, tingcard=0, isgang=0, card=101, left_count=106}
			System.out.println("轮到座位号:" + param.getInt("seat") + "的用户摸牌" + ",牌为：" + param.getInt("card"));
			if (param.getInt("seat") != null && seat == param.getInt("seat")) {
				cardInhand.add(param.getInt("card"));
			}
		}
		return null;
	}

	/**
	 * 初始化手牌协议 811
	 * 
	 * @param command
	 * @param message
	 * @return
	 */
	public static String cardInHead(String command, Message message) {
		if (command.equalsIgnoreCase("811")) {
			ITObject param = message.param;
			if (param == null)
				return null;
//            {bank_seat=1, laiziCard=0, laiziCard2=0, laiziCard2Before=0, jing=0, laiziCardBefore=0, card_list=[101, 103, 104, 201, 204, 207, 208, 209, 307, 309, 501, 502, 503]} 
			ITArray cardList = param.getTArray("card_list");
			for (int i = 0; i < cardList.size(); i++) {
				cardInhand.add(cardList.getInt(i));
			}
			if (cardInhand.size() > 13) {
				outCard(command, message);
				System.out.println("机器人:" + param.getInt("seat") + "为庄家，需要出牌" + ",牌为：" + cardInhand.get(0));

			}
			System.out.println("机器人:" + param.getInt("seat") + "初始化手牌" + ",牌为：" + cardInhand.toString());

		}
		return null;
	}

	public static String outCard(String command, Message message) {
		ITObject params = TObject.newInstance();
		params.putString("session", session + "," + token);
		params.putInt("card1", 0);
		params.putInt("card", cardInhand.get(0));
		cardInhand.remove(0);
		System.out.println("目前剩余手牌：" + cardInhand.toString());
		client.send("611", params, response -> {
			System.out.println("出牌成功: " + response.returnCode);
		});
		return null;
	}

	public static String actionCard(String command, Message message) {
		ITObject params = TObject.newInstance();
		params.putString("session", session + "," + token);
		params.putInt("qi", 0);
		params.putInt("id", 0);
		cardInhand.remove(0);
		cardInhand.remove(1);
		System.out.println("执行id为：" + 0+"的操作");

		client.send("612", params, response -> {
			System.out.println("操作成功: " + response.returnCode);
		});
		return null;
	}

	public static String ready() {
		try {
			// 添加2秒延迟
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		cardInhand = new ArrayList<Integer>();

		System.out.println("准备");
		ITObject params = TObject.newInstance();
		params.putString("session", session + "," + token);

		client.send("1003", params, new ICallback<MessageResponse>() {

			@Override
			public void action(MessageResponse messageResponse) {
				System.out.println("准备成功: ");

				System.out.println(messageResponse);
				System.out.println(messageResponse.returnCode);
				System.out.println(messageResponse.messageData.param);
			}
		});
		return null;
	}

	public static String joinRoom() {
		try {
			// 添加2秒延迟
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		ITObject params = TObject.newInstance();
		params.putString("session", session + "," + token);

		System.out.println("进入房间");
		client.send("1002", params, response -> {
			System.out.println("进入房间成功: " + response.returnCode);
			System.out.println(response.returnCode);
			System.out.println(response.messageData.param);
			ITObject obj = response.messageData.param.getTObject("tableInfo");

			ITArray array = obj.getTArray("playerData");
			for (int i = 0; i < array.size(); i++) {
				System.out.println(array.getTObject(i).getInt("seat"));
				if (playerId == array.getTObject(i).getInt("aid")) {
					seat = array.getTObject(i).getInt("seat");

				}
			}
		});
		return null;
	}

	public static void sleepTime(int time) {
		try {
			// 添加2秒延迟
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		try {
			PluginService.me().loadConfig();
		} catch (Exception e1) {
			e1.printStackTrace();
		}

//		NetManager.debug_print = false;
//		NetManager.TIMEOUT_TIME = 10;
//		NetManager.VERSION = 10;

		tcp_test();

		while (true) {
			NetManager.processEvents();
			try {
				Thread.sleep(8);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
