/*******************************************************************************
 * Copyright (c) 2008 IBM Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.cosmos.internal.dr.drs.service.handler.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.eclipse.cosmos.provisional.dr.drs.service.handler.common.AbstractServletHandler;
import org.eclipse.cosmos.provisional.dr.drs.service.handler.common.IParameters;


public class LogURLResponse extends AbstractServletHandler {

	protected String testHandlerDir = ""; //$NON-NLS-1$
	
	@Override
	public void doGet(HttpServletRequest req, StringWriter resp)
			throws ServletException, IOException {
		delegateRequest(req, resp);
	}

	@Override
	public void doPost(HttpServletRequest req, StringWriter resp)
			throws ServletException, IOException {
		delegateRequest(req, resp);
	}
	
	protected  void delegateRequest(HttpServletRequest req, StringWriter resp)
	throws ServletException, IOException {
		if ((testHandlerDir!= null) || (!(testHandlerDir.trim().equals("")))){ //$NON-NLS-1$
			String service = req.getParameter("service"); //$NON-NLS-1$
			IParameters parameters = new RequestParametersImpl(req);
			Map parametersMap = parameters.getParameterMap();
			Iterator iter = parametersMap.keySet().iterator();
			File testDir = new File (testHandlerDir+service);
			if (!testDir.exists())
				testDir.mkdirs();
			int count = 1;
			File inputFile = new File(testHandlerDir+service+"/test"+count+".input"); //$NON-NLS-1$ //$NON-NLS-2$
			while (inputFile.exists()){
				count++;
				inputFile = new File(testHandlerDir+service+"/test"+count+".input"); //$NON-NLS-1$ //$NON-NLS-2$
			}
			File outputFile = new File(testHandlerDir+service+"/test"+count+".output"); //$NON-NLS-1$ //$NON-NLS-2$
			BufferedWriter writer = new BufferedWriter(new FileWriter(inputFile));			
			while (iter.hasNext()){
				Object key = iter.next();
				writer.write(key + "=" +req.getParameter((String)key)); //$NON-NLS-1$
				writer.newLine();
			}		
			writer.close();
			FileWriter fw = new FileWriter(outputFile);
			fw.write(resp.getBuffer().toString());
			fw.close();
		}
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		testHandlerDir = config.getServletContext().getInitParameter("TESTHANDLER_DIR"); //$NON-NLS-1$
		super.init(config);
	}
	
}
