/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.enterprise.diagnostics.util;
import java.io.File;
import java.util.Comparator;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;

import com.sun.enterprise.diagnostics.Constants;

/**
 * Sorts server.log files in the ascending order by date.
 * @author Manisha Umbarje
 */
public class LogNameComparator implements Comparator  {

    private static final SimpleDateFormat dateFormat = 
    new SimpleDateFormat(Constants.DATE_PATTERN);
    
    public LogNameComparator() {
    }

    public int compare(Object obj1 , Object obj2) {
	String name1 = ((File)obj1).getName();
	String name2 = ((File)obj2).getName();

	if (name1 == null || name2 == null)
	    return 0;

	//Log Files are in the format server.log_yyyy-mm-ddThh-mm-ss
	int name1DateBeginIndex = name1.indexOf
				(Constants.FILENAME_DATE_SEPARATOR)  + 1;
	int name2DateBeginIndex = name2.indexOf
				(Constants.FILENAME_DATE_SEPARATOR) + 1;

	// obj1 represents server.log i.e latest file
	if (name1DateBeginIndex <=  0) {
	    return 1;
	}

	// obj2 represents server.log i.e latest file
	if(name2DateBeginIndex <= 0) {
	    return -1;
	}

	try {
	    Date name1Date = dateFormat.parse
		(name1.substring
		(name1DateBeginIndex,name1DateBeginIndex + 
		Constants.ENTRY_DATE_LENGTH));
	    
	    Date name2Date = dateFormat.parse
		(name2.substring
		(name2DateBeginIndex,name1DateBeginIndex + 
		Constants.ENTRY_DATE_LENGTH));

	    if (name1Date.after(name2Date))
		return 1;
	    else
		return -1;
	} catch (ParseException exc) {
	    return 0;
	}
    }
}
