/*******************************************************************************
 * 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.FileWriter;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;

import org.eclipse.cosmos.provisional.dr.ps.common.IConstants;

public class SaverHelper {
	public static void saveQuery(String query, String uuid, String title, String nodeClass, String parentClass, String rootDir ,boolean isFolder) throws Exception{
		String containerName = rootDir+File.separator+parentClass;
		File container = new File(containerName);
		container.mkdirs();
		File jprop = new File(containerName+File.separator+uuid+"."+IConstants.PROPEXT); //$NON-NLS-1$
		File queryFile = new File(containerName+File.separator+uuid+"."+IConstants.QUERYEXT); //$NON-NLS-1$
		//create the directory if it doesn not exist
		FileWriter writer = null;
		try {
			//write query file
			writer = new FileWriter(queryFile);
			writer.write(query);
		} finally  {
			if (writer != null)
				writer.close();
		}
		
		FileWriter jpropWriter = null;
		//write jprop file
		String jpropContent = "{nodeClass:\""+nodeClass+"\", title:\""+title+"\", services:\"__inherit__\", uuid:\""+uuid+"\", isFolder:"+isFolder+"}"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
		try{
			jpropWriter = new FileWriter(jprop);
			jpropWriter.write(jpropContent);
		} finally  {
			if (jpropWriter != null)
				jpropWriter.close();
		}
	}
	
	public static void renameQuery(String uuid, String title, String nodeClass, String parentClass, String rootDir, boolean isFolder) throws Exception{
		String containerName = rootDir+File.separator+parentClass;
		File jprop = new File(containerName+File.separator+uuid+"."+IConstants.PROPEXT); //$NON-NLS-1$
		if (jprop.isFile()){
			FileWriter jpropWriter = null;
			//write jprop file
			String jpropContent = "{nodeClass:\""+nodeClass+"\", title:\""+title+"\", services:\"__inherit__\", uuid:\""+uuid+"\", isFolder:"+isFolder+"}"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
			try{
				jpropWriter = new FileWriter(jprop);
				jpropWriter.write(jpropContent);
			} finally  {
				if (jpropWriter != null)
					jpropWriter.close();
			}
		}
	}
	
	public static void deleteQuery(String uuid, String parentClass, String rootDir) throws Exception{
		String containerName = rootDir+File.separator+parentClass;
		File jprop = new File(containerName+File.separator+uuid+"."+IConstants.PROPEXT); //$NON-NLS-1$
		if (jprop.isFile()){
			//delete file
			jprop.delete();
		}
		File queryFile = new File(containerName+File.separator+uuid+"."+IConstants.QUERYEXT); //$NON-NLS-1$
		if (queryFile.isFile()){
			//delete file
			queryFile.delete();
		}
		
	}
	
	
	public static File[] getSortedFileList(File dir, FilenameFilter filter){
		  File[] files = dir.listFiles(filter);
		  Arrays.sort(files, new Comparator() {
		    public int compare(Object o1, Object o2) {
		      File f1 = (File) o1; File f2 = (File) o2;
		      return (int) (f2.lastModified() - f1.lastModified());
		    }
		  });
		  return files;
	}

	public static void saveResponse(String response, String uuid, String rootDir, int limit) throws Exception{		
		String uuidDirname = rootDir+File.separator+IConstants.RESPONSEDIR+File.separator+uuid;
		File uuidDir = new File(uuidDirname);
		//need to check limit
		if (limit != -1){
			if (uuidDir.isDirectory()){
				
				   
			    FilenameFilter filter = new FilenameFilter() {
			        public boolean accept(File dir, String name) {
			            return name.endsWith(IConstants.RESPONSEEXT);
			        }
			    };
			    File[] children = getSortedFileList(uuidDir, filter);
			    if (children.length >= limit){
			    	
			    	int childrenLength = children.length;
			    	if (limit > 0){
				    	for (int x = (limit-1); x < childrenLength; x++){
				    		children[x].delete();
				    	}
			    	}
			    }
			}
		}
		//should not save anything if limit equals 0
		if (limit == 0) return;
		uuidDir.mkdirs();

		long timestamp = Calendar.getInstance().getTimeInMillis();
		File responseFile = new File(uuidDirname+File.separator+timestamp+"."+IConstants.RESPONSEEXT); //$NON-NLS-1$
		//create the directory if it doesn not exist
		FileWriter writer = null;
		try {
			//write query file
			writer = new FileWriter(responseFile);
			writer.write(response);
		} finally  {
			if (writer != null)
				writer.close();
		}		
	}
		

}
