/*******************************************************************************
 * Copyright (c) 2007, 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.outputter;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;

import org.eclipse.cosmos.provisional.dr.drs.service.handler.common.AbstractOutputter;
import org.eclipse.cosmos.provisional.dr.drs.service.handler.common.IOutputterContext;
import org.eclipse.cosmos.provisional.dr.drs.service.handler.common.IParameters;
import org.w3c.dom.Element;

public class ReportDeployment extends AbstractOutputter {
	protected IOutputterContext context;

	@Override
	public void initalize(IOutputterContext context, IParameters parameters)
			throws Exception {
		super.initalize(context, parameters);
		this.context = context;
		setupReportContext(context);
	}

	public void render(PrintWriter output, IParameters input) throws Exception {
		String func = input.getParameter("func"); //$NON-NLS-1$
		if (func != null){
			if (func.equals("list")) //$NON-NLS-1$
				this.generateReportList(output, input);
			if (func.equals("datasource")) //$NON-NLS-1$
				this.datasource(output, input);
			else if (func.equals("url")){ //$NON-NLS-1$
				this.generateURL(output, input);
			}
		}
	}

	protected void generateReportList(PrintWriter out, IParameters input) throws ServletException, IOException {
		String reportURL = context.getInitParameter("COSMOS_REPORT_URL"); //$NON-NLS-1$
		Map parameters = input.getParameterMap();
		Iterator param = parameters.keySet().iterator();
		String paramStr= ""; //$NON-NLS-1$
		while (param.hasNext()){
			Object key = param.next();
			//need to handle datasource parameter as a special case
			if (key.equals("service")){
				continue;
			}
			else{
				paramStr += "&"+key+"="+URLEncoder.encode(input.getParameter(key.toString()),"UTF-8"); //$NON-NLS-1$ //$NON-NLS-2$
			}
		}
		sendRequest(reportURL+"/webcontent/report.jsp?func=list"+paramStr, out); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
		out.close();
	}
	
	protected void sendRequest(String url, PrintWriter pw) throws IOException{

		java.net.URL netUrl = new java.net.URL(url);


		HttpURLConnection connection = (HttpURLConnection) netUrl.openConnection();

		connection.setRequestMethod( "GET" );
		connection.setUseCaches(false);
		connection.setDoInput(true);

		connection.setDoOutput(true);


		DataOutputStream out = new DataOutputStream( connection.getOutputStream() );

		out.flush();
		out.close();


		BufferedReader reader = new BufferedReader( new InputStreamReader(
		connection.getInputStream() ) );

		String response = reader.readLine();


		while( null != response )
		{			
			pw.write(response);
			response = reader.readLine();

		}		
	}
	
	protected void sendPOSTRequest(String url, PrintWriter pw, String parameters) throws IOException{

		java.net.URL netUrl = new java.net.URL(url);


		HttpURLConnection connection = (HttpURLConnection) netUrl.openConnection();
	    connection.setRequestMethod("POST");
	    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				
	    connection.setRequestProperty("Content-Length", "" + Integer.toString(parameters.getBytes().length));
	    connection.setRequestProperty("Content-Language", "en-US");  
		connection.setUseCaches(false);
		connection.setDoInput(true);

		connection.setDoOutput(true);

	      //Send request
		DataOutputStream out = new DataOutputStream( connection.getOutputStream() );
		out.writeBytes (parameters);

		out.flush();
		out.close();


		BufferedReader reader = new BufferedReader( new InputStreamReader(
		connection.getInputStream() ) );

		String response = reader.readLine();


		while( null != response )
		{			
			pw.write(response);
			response = reader.readLine();

		}		
	}
	
    
	protected void generateURL(PrintWriter out, IParameters input) throws ServletException, IOException {
		String reportURL = context.getInitParameter("COSMOS_REPORT_URL"); //$NON-NLS-1$
		Map parameters = input.getParameterMap();
		Iterator param = parameters.keySet().iterator();
		String paramStr= ""; //$NON-NLS-1$
		int count = 0;
		while (param.hasNext()){
			String key = (String)param.next();
			if (count == 0)
				paramStr += "?"; //$NON-NLS-1$ 
			else
				paramStr += "&"; //$NON-NLS-1$ 
			paramStr += key+"="+input.getParameter(key.toString()); //$NON-NLS-1$ //$NON-NLS-2$
			count++;
		}
		out.print(reportURL+"/webcontent/report.jsp"+paramStr);
		out.close();		
	}
	
	protected void datasource(PrintWriter out, IParameters input) throws ServletException, IOException {
		String reportURL = context.getInitParameter("COSMOS_REPORT_URL"); //$NON-NLS-1$
		Map parameters = input.getParameterMap();
		Iterator param = parameters.keySet().iterator();
		String paramStr= ""; //$NON-NLS-1$
		int count = 0;
		while (param.hasNext()){
			String key = (String)param.next();
			if (count == 0)
				paramStr += ""; //$NON-NLS-1$ 
			else
				paramStr += "&"; //$NON-NLS-1$ 
			paramStr += key+"="+input.getParameter(key.toString()); //$NON-NLS-1$ //$NON-NLS-2$
			count++;
		}
		sendPOSTRequest(reportURL+"/report.jsp", out,paramStr);
		out.close();		
	}
	
	
	protected void setupReportContext(IOutputterContext context) throws ServletException {
		if (context.getStore().getAttribute("COSMOS_REPORT_REGISTRY") == null){ //$NON-NLS-1$
			ReportDeploymentHandler rdh = new ReportDeploymentHandler();
			String filename = context.getInitParameter("COSMOS_REPORT_DEPLOYMENT_FILE"); //$NON-NLS-1$
			rdh.parse(context.getRealPath(filename));
			context.getStore().setAttribute("COSMOS_REPORT_TEMPLATE_LOOKUP", rdh); //$NON-NLS-1$
		}
	}
		
}
