/*
 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.sun.ts.tests.websocket.spec.application.lifecycle;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;

public class InnerEndpoint extends Endpoint implements
		MessageHandler.Whole<String> {

	protected String receivedMessage = "";
	protected CountDownLatch latch;
	private Session session;

	public InnerEndpoint(CountDownLatch latch) {
		super();
		this.latch = latch;
	}

	@Override
	public void onOpen(Session session, EndpointConfig config) {
		session.addMessageHandler(this);
		this.session = session;
	}

	@Override
	public void onMessage(String message) {
		this.receivedMessage += message;
		latch.countDown();
	}

	public String getReceivedMessage() {
		return receivedMessage;
	}

	public void sendMessage(String message) {
		try {
			session.getBasicRemote().sendText(message);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public void await(long seconds) {
		try {
			latch.await(seconds, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

}
