/*
 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * $Id: WSCCloseSessionServer.java 72811 2013-09-05 13:41:31Z supol $
 */
package com.sun.ts.tests.websocket.spec.application.closing;

import java.io.IOException;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.sun.ts.tests.websocket.common.util.IOUtil;

@ServerEndpoint(value = "/closesession")
public class WSCCloseSessionServer {
	static int lastCloseCode = 0;

	static final String MESSAGES[] = { "idle", "lastcode" };

	@OnMessage
	public String onMessage(String msg, Session session) {
		if (MESSAGES[0].equals(msg)) {
			setLastCloseCode(0);
			session.setMaxIdleTimeout(1);
		} else if (MESSAGES[1].equals(msg))
			msg = getLastCloseCode();
		return msg;
	}

	@OnError
	public void onError(Session session, Throwable thr) throws IOException {
		thr.printStackTrace(); // Write to error log, too
		String message = IOUtil.printStackTrace(thr);
		session.getBasicRemote().sendText(message);
	}

	@OnClose
	public void onClose(CloseReason reason) {
		int lastCloseCode = reason.getCloseCode().getCode();
		setLastCloseCode(lastCloseCode);
	}

	private static String getLastCloseCode() {
		return String.valueOf(lastCloseCode);
	}

	private static void setLastCloseCode(int lastCloseCode) {
		WSCCloseSessionServer.lastCloseCode = lastCloseCode;
	}

}
