package de.ivu.elect.presentation.security.sso;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import de.ivu.elect.presentation.security.LoginView;

public class SingleSignOnRedirectServletResponse extends HttpServletResponseWrapper {

  public static final String REDIRECT = "<html><meta http-equiv=\"refresh\" content=\"0;url=" + LoginView.VIEW_ID.substring(1) + "\"></html>";

  public static final int AUTHENTICATE = 401;

  private boolean redirectSent = false;

  public SingleSignOnRedirectServletResponse(HttpServletResponse response) {
    super(response);
  }

  @Override
  public void setStatus(int sc) {
    super.setStatus(sc);
    // Falls der Browser kein Login-Token anbieten kann, redirect auf die normale Login-Seite...
    if (sc == AUTHENTICATE) {
      redirectLoginSeite();
    }
  }

  public void redirectLoginSeite(){
    try {
      setContentType("text/html");
      getWriter().append(REDIRECT);
      flushBuffer();
      redirectSent = true;
    } catch (IOException e) {
      throw new RuntimeException(e.getMessage(), e);
    }
  }

  @Override
  public void setContentLength(int len) {
    if (!redirectSent) {
      super.setContentLength(len);
    }
  }

}
