/* $Id: PropFindSort.java 125 2011-03-09 09:49:51Z ohura $ */
package webdav.table;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

import webdav.PropFindInfo;

public class PropFindSort {

	public PropFindInfo[] sort(PropFindInfo[] propFindInfos){
		if(propFindInfos == null){
			return null;
		}
		ArrayList dir = new ArrayList();
		ArrayList file = new ArrayList();
		
		for(int i=0;i<propFindInfos.length;i++){
			PropFindInfo propFindInfo = propFindInfos[i];
			if(propFindInfo.isDirectory()){
				dir.add(propFindInfo);
			}else{
				file.add(propFindInfo);
			}
		}
		ArrayList resultList = new ArrayList();
		if(dir.size() != 0){
			Object[] dirsInfo = dir.toArray();
			Arrays.sort(dirsInfo, new PropFindSortComparator());
			for(int i=0;i<dirsInfo.length;i++){
				resultList.add(dirsInfo[i]);
			}
		}
		if(file.size() != 0){
			Object[] filesInfo = file.toArray();
			Arrays.sort(filesInfo, new PropFindSortComparator());
			for(int i=0;i<filesInfo.length;i++){
				resultList.add(filesInfo[i]);
			}
		}
		if(resultList.size() != 0){
			PropFindInfo[] resultPropFindInfos = new PropFindInfo[resultList.size()];
			for(int i=0;i<resultList.size();i++){
				resultPropFindInfos[i] = (PropFindInfo)resultList.get(i);
			}
			return resultPropFindInfos;
		}
		return null;
	
	}
	
	class PropFindSortComparator implements Comparator{

		public int compare(Object arg0, Object arg1) {
			PropFindInfo propFindInfo0 = (PropFindInfo)arg0;
			PropFindInfo propFindInfo1 = (PropFindInfo)arg1;
			String displayname0 = propFindInfo0.getDisplayname();
			String displayname1 = propFindInfo1.getDisplayname();
			return displayname0.compareTo(displayname1);
		}
		
	}
	
}
