package nxm.webvnc.lib;

import javax.net.ssl.SSLSocket;

import nxm.sys.net.HPage;

/**
 * Handles REST requests to open vnc sessions
 *
 * @author adw
 * @since NeXtMidas 4.1.1
 *
 */
public class NewInstanceHandler implements RequestHandlerInterface {
  private VNCSessionManager sessionManager;

  /** Constructor
   *
   *  @param sessionManager The {@link VNCSessionManager} to use
   */
  public NewInstanceHandler (VNCSessionManager sessionManager) {
    this.sessionManager = sessionManager;
  }

  /** Handle the REST request.
   *
   *  @param uri  The URI used to access this resource.
   *  @param hp   The {@link HPage} representing the request.
   *  @return The data to be returned to the client.
   */
  @Override
  public String handleRequest (String uri, HPage hp) {
    String DN = null;
    try {
      SSLSocket sslsock = (SSLSocket) hp.getSocket();
      DN = sslsock.getSession().getPeerPrincipal().getName();
    } catch (Exception e) {
      if (sessionManager.isSSL()) {
        e.printStackTrace(); // TODO switch to SEVERE LOG
      }
    }
    return String.valueOf(sessionManager.getVNCSession(DN, hp.getRequestHeader()));
  }
}
