/*******************************************************************************
 * 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.File;
import java.io.FilenameFilter;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

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.eclipse.cosmos.provisional.dr.ps.common.IConstants;

public class ReponseHistoryOutputter extends AbstractOutputter {
	public static final String QUERY_ID="uuid"; //$NON-NLS-1$
	protected String rootDir;
	
	public void initalize(IOutputterContext context, IParameters parameters) throws Exception {
		this.rootDir = context.getRealPath(IConstants.QUERYREPO+File.separator + IConstants.RESPONSEDIR);		
		super.initalize(context, parameters);
	}

	public void render(PrintWriter output, IParameters input) throws Exception {
		String uuid = input.getParameter(QUERY_ID);
		String genRepoFilename = rootDir+File.separator + uuid;
		File fileExists = new File(genRepoFilename);
		if (fileExists.exists() && fileExists.isDirectory()){
			FilenameFilter fileFilter = new FilenameFilter() {
		        public boolean accept(File dir, String name) {
			        	return (name.endsWith(IConstants.RESPONSEEXT));
			        }
			    };				
		     File[] repoFiles = SaverHelper.getSortedFileList(fileExists, fileFilter);
		    output.write("["); //$NON-NLS-1$
		    for (int x = 0; x < repoFiles.length; x++){
		    	if (x > 0)
		    		output.write(","); //$NON-NLS-1$
		    	generateResponseJSON(repoFiles[x], output, uuid);
		    }
		    output.write("]"); //$NON-NLS-1$
		    
		}
		
	}
	
	protected String generateTimeStamp(String timestamp,Locale locale ){
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(Long.parseLong(timestamp));
		SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", locale); //$NON-NLS-1$
		return sdf.format(cal.getTime());
		
	}
	protected void generateResponseJSON(File file, Writer writer, String uuid) throws Exception{
		if (file.isFile()){
			String timestamp = file.getName();
			int idx = timestamp.indexOf("."+IConstants.RESPONSEEXT); //$NON-NLS-1$
			if (idx != -1)
				timestamp = timestamp.substring(0, idx);
			writer.write("{title:\""+generateTimeStamp(timestamp, Locale.ENGLISH)+"\", instanceId:\""+timestamp+"\", uuid:\""+uuid+"\"}"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$


		}
		
	}
	
	/**
	 * Return a valid UTF8 xml encoded string from the input string buffer 
	 * provided.
	 * 
	 * @param buffer The <code>StringBuffer</code> to encode.
	 * @return The encoded string.
	 */
	public static String escapeForMarkup(byte[] buffer) {
		if (buffer == null) {
			return null;
		}
		final StringBuffer result = new StringBuffer();
		char c;
		int len = buffer.length;
		for (int i = 0; i < len; i++) {
			c = (char)buffer[i];
			switch (c) {
				case '"' :
					result.append("\\\""); //$NON-NLS-1$
					break;
				case '\r' :
					break;
				case '\n' :
					break;
				default :
						result.append(c);
			}
		}
		return result.toString();
	}	

}
