package game.net.test2;

import game.constant.GameConstant;

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

import com.haru.net.NetConstant;





public class GameServerManager extends Thread implements NetConstant {

	private GameServer server1;
	private GameServer server2;
	private Socket sock1;
	private Socket sock2;



	// テスト用にサーバソケットが二種類いる
	private ServerSocket svsocket1;
	private ServerSocket svsocket2;



	public GameServerManager(GameServer server1, GameServer server2) {

		this.server1 = server1;
		this.server2 = server2;

		svsocket1 = server1.create(PORT1);
		svsocket2 = server1.create(PORT2);

	}

	public boolean listen() {

		//--------------------------------------------------------------------------//
		// ここはスレッド化する

		System.out.println("クライアント1の接続待機");
		if (sock1 == null) {
			sock1 = server1.listen(svsocket1);
		}

		System.out.println("クライアント2の接続待機");
		if (sock2 == null || sock2.isClosed()) {
			sock2 = server2.listen(svsocket2);
		}

		if (sock1 == null) {
			return false;
		}
		if (sock2 == null) {
			return false;
		}
		//--------------------------------------------------------------------------//




		System.out.println("接続完了");
		server1.setOther(server2);
		server2.setOther(server1);
		return true;
	}





	//--------------------------------------------------------------------------//
	// ゲーム開始後
	//--------------------------------------------------------------------------//


	private boolean isEnd = false;
	public void setEnd(boolean flag) {
		isEnd = flag;
	}

	final public void run() {
		gameinit();

		boolean flag = true;

		while (!isEnd && flag) {

			flag =  gameloop();

			try {
				Thread.sleep(1000 / GameConstant.FPS);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		gameend();
	}

	//--------------------------------------------------------------------------//

	protected void gameinit() {
		server1.gameinit();
		server2.gameinit();
	}


	private static int loop1 = 0;
	private static int loop2 = 0;
	protected boolean gameloop() {


		boolean flag1 = server1.gameloop(loop1 ++);
		boolean flag2 = server2.gameloop(loop2 ++);


		try {
			if (!flag1) {
			sock1.close();

			}

			if (!flag2) {
				sock2.close();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return flag1 && flag2;
	}

	protected void gameend() {
		server1.gameend();
		server2.gameend();



	}


}