package jp.agentec.abook.abv.bl.websocket;

import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import jp.agentec.abook.abv.bl.common.log.Logger;

import org.java_websocket.client.DefaultSSLWebSocketClientFactory;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;

public class DefaultWebSocketClient extends WebSocketClient {
	private static final String TAG = "DefaultWebSocketClient";
	public static List<String> log = new ArrayList<String>(); // for debug
	private MeetingManager meetingManager;

	public DefaultWebSocketClient(URI serverUri, Draft draft, MeetingManager meetingManager) throws NoSuchAlgorithmException, KeyManagementException {
		super(serverUri, draft);
		this.meetingManager = meetingManager;
		if (serverUri.getScheme().startsWith("wss")) {
			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null, new TrustManager[]{new CheatTrustManager()}, null);
			setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sslContext));
		}
	}

	@Override
	public void onClose(int code, String reason, boolean remote) {
//		log.add("[onClose]: (" + Thread.currentThread().getId() + ") " + " code=" + code + " reason=" + reason + " remote:" + remote); // 負荷テスト用：通常はコメントアウト
		Logger.d(TAG, "[onClose]: (%s) code=%s reason=%s remote:%s", Thread.currentThread().getId(), code, reason, remote);
		meetingManager.onClose(code, reason, remote);
	}

	@Override
	public void onError(Exception e) {
//		log.add("[onError]" + e.toString()); // 負荷テスト用：通常はコメントアウト
		Logger.e(TAG, "[onError]", e);
		meetingManager.onError(e);
	}

	@Override
	public void onMessage(String message) {
		Logger.d(TAG, "[onMessage]: (%s) %s", Thread.currentThread().getId(), message);
		meetingManager.onMessage(message);
	}

	@Override
	public void onOpen(ServerHandshake handshake) {
//		log.add("[onOpen]: (" + Thread.currentThread().getId() + ") " +  handshake.getHttpStatusMessage()); // 負荷テスト用：通常はコメントアウト
		Logger.d(TAG, "[onOpen]: (%s) %s", Thread.currentThread().getId(), handshake.getHttpStatusMessage());
		// OK: Switching Protocols
		meetingManager.onOpen(handshake);
	}

}
