package test.abnahme;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

import test.MOAIDTestCase;

import at.gv.egovernment.moa.id.MOAIDException;
import at.gv.egovernment.moa.id.auth.AuthenticationServer;
import at.gv.egovernment.moa.id.config.ConfigurationProvider;
import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider;
import at.gv.egovernment.moa.id.data.AuthenticationData;

/**
 * Base class for MOA ID test cases.
 * 
 * Provides some utility functions.
 * 
 * @author Stefan Knirsch
 * @version $Id$
 */
public class AbnahmeTestCase extends MOAIDTestCase {

  protected static final String TESTDATA_ROOT = "data/abnahme-test/";
  protected static final String TESTDATA_XMLDATA = "data/abnahme-test/xmldata/";
  protected static final String AUTH_ENDPOINT = "http://localhost:8080/moa-id-auth/";
  protected AuthenticationServer server;

  /**
   * Constructor for MOATestCase.
   * @param arg0
   */
  public AbnahmeTestCase(String name) {
    super(name);
  }
  /**
   * Set up a transaction context with a test configuration.
   */
  protected void setUp() throws Exception {

    System.out.print("--------S-T-A-R-T----V-O-N----");
    System.out.print(getName().toUpperCase().substring(4,getName().length()));
    System.out.print("-----------------------------\n");

    // Set moa.spss.server.configuration property
    System.setProperty("moa.spss.server.configuration",TESTDATA_ROOT + "conf/moa/ConfigurationTest.xml");

    // Set moa.id.configuration property
    String pathname = findXmldata("Configuration.xml");
    System.setProperty(ConfigurationProvider.CONFIG_PROPERTY_NAME, pathname);
    System.out.println("Konfiguration " + pathname);
    AuthConfigurationProvider.reload();

    server = AuthenticationServer.getInstance();
  }
  /** Test case z.B. "A153" */
  protected String getID() {
    return getName().toUpperCase().substring(4,getName().length());
  }
  /** Test group z.B. "A100" */
  protected String getTestGroup() {
    return getID().substring(0, 2) + "00";
  }
  /** Test case data directory */ 
  protected String getTestCaseDirectory() {
    return getTestGroupDirectory() + getID() + "/";
  }
  /** Test group data directory */
  protected String getTestGroupDirectory() {
    return TESTDATA_XMLDATA + getTestGroup() + "/";
  }
  /** Finds a file in the xmldata directory */
  protected String findXmldata(String filename) {
    String pathname = getTestCaseDirectory() + filename;
    if (! new File(pathname).exists()) {
      pathname = getTestGroupDirectory() + filename;
      if (! new File(pathname).exists()) {
        pathname = TESTDATA_XMLDATA + filename;
      }
    }
    return pathname;
  }
  /** Finds and reads a file in the xmldata directory */
  protected String readXmldata(String filename) throws IOException {
    String pathname = findXmldata(filename);
    System.out.println("Read file " + pathname);
    return readFile(pathname);
  }
  protected void writeXmldata(String filename, byte[] content) throws Exception {
    String pathname = getTestCaseDirectory() + filename;
    System.out.println("Write file " + pathname);
    RandomAccessFile raf = new RandomAccessFile(pathname, "rw");
    byte[] data = content;
    raf.write(data);
    raf.setLength(data.length);
    raf.close();  
  }
  
  /**
   * Creates a session using standard parameters,
   * and returns the session ID.
   */
  protected String startAuthentication() throws MOAIDException {
    return startAuthentication("https://localhost:9443/");
  }
   /**
   * Creates a session using standard parameters,
   * and returns the session ID.
   */
  protected String startAuthentication(String oaURL) throws MOAIDException {
    String htmlForm = AuthenticationServer.getInstance().startAuthentication(
      "https://localhost:8443/auth",
      "gb",
      oaURL,
      null,
      null,
      null);
    String sessionID = parseSessionIDFromForm(htmlForm);
    return sessionID;
  }
  private String parseSessionIDFromForm(String htmlForm) {
    String parName = "MOASessionID=";
    assertTrue(
      "HTML Form enth�lt keine SessionID",
      htmlForm.indexOf(parName) >= 0);
    int i1 = htmlForm.indexOf(parName) + parName.length();
    int i2 = i1; 
    while(i2 < htmlForm.length() && 
          (htmlForm.charAt(i2) == '-' || (htmlForm.charAt(i2) >= '0' && htmlForm.charAt(i2) <= '9')))
      i2++;
    assertTrue("HTML Form enth�lt keine g�ltige SessionID", i2 > i1);
    return htmlForm.substring(i1, i2);
  }
  protected String clearSessionID(String htmlForm) {
    String sessionID = parseSessionIDFromForm(htmlForm);
    int i1 = htmlForm.indexOf(sessionID);
    int i2 = i1 + sessionID.length();
    return htmlForm.substring(0, i1) + htmlForm.substring(i2);
  }
  protected void assertEqualsIgnoreSessionID(String s1, String s2) {
    String ss1 = clearSessionID(s1);
    String ss2 = clearSessionID(s2);
    assertEquals(ss1, ss2);
  }
  protected void authDataWriter(AuthenticationData authData, String filename) throws Exception
  {
    writeXmldata("AuthenticationDataNEW.xml", clearSamlAssertion(authData.getSamlAssertion()).getBytes("UTF-8"));
  }

  /**
   * clearSamlAssertion l�scht aus einer beliebiegen String-Repr�sentation einer XML-Struktur
   * AUSSLIESSLICH die Attribute 'IssueInstant' und 'AssertionID' heraus.
   * @param samlAssertion
   * @return String
   */
  protected String clearSamlAssertion(String samlAssertion)
  {
    String result = killInclusive(samlAssertion,"IssueInstant='", "'","");
    result = killInclusive(result,"AssertionID='", "'","");
    return result;  
  }  
}