
package com.beem.project.beem.otr;

import net.java.otr4j.OtrEngineHost;
import net.java.otr4j.OtrEngineListener;
import net.java.otr4j.OtrException;
import net.java.otr4j.session.Session;
import net.java.otr4j.session.SessionID;
import net.java.otr4j.session.SessionImpl;
import net.java.otr4j.session.SessionStatus;

import java.security.PublicKey;
import java.util.Hashtable;
import java.util.Map;

public class OtrEngine {

	public OtrEngine(OtrEngineHost host, OtrEngineListener listener) {
		this.host = host;
		this.listener = listener;
	}

	private OtrEngineHost host;
	private Map<SessionID, Session> sessions;

	private Session getSession(SessionID sessionID) {

		if (sessionID == null || sessionID.equals(SessionID.Empty))
			throw new IllegalArgumentException();

		if (sessions == null)
			sessions = new Hashtable<SessionID, Session>();

		if (!sessions.containsKey(sessionID)) {
			Session session = new SessionImpl(sessionID, host);
			sessions.put(sessionID, session);

			session.addOtrEngineListener(listener);
			return session;
		} else
			return sessions.get(sessionID);
	}

	public SessionStatus getSessionStatus(SessionID sessionID) {
		return this.getSession(sessionID).getSessionStatus();
	}

	public String transformReceiving(SessionID sessionID, String msgText)
			throws OtrException {
		return this.getSession(sessionID).transformReceiving(msgText);
	}

	public String[] transformSending(SessionID sessionID, String msgText)
			throws OtrException {
		return this.getSession(sessionID).transformSending(msgText, null);
	}

	public void endSession(SessionID sessionID) throws OtrException {
		this.getSession(sessionID).endSession();
	}

	public void startSession(SessionID sessionID) throws OtrException {
		this.getSession(sessionID).startSession();
	}

	public void refreshSession(SessionID sessionID) throws OtrException {
		this.getSession(sessionID).refreshSession();
	}

	public PublicKey getRemotePublicKey(SessionID sessionID) {
		return this.getSession(sessionID).getRemotePublicKey();
	}

	private final OtrEngineListener listener;
}
