/*******************************************************************************
 * Copyright 2014 Centre for Development of Advanced Computing(C-DAC), Pune
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package in.cdac.medinfo.csnotk.csnolib.util;

import in.cdac.medinfo.csnotk.csnolib.model.Description;

import java.util.Comparator;

/**
 *  The class compares two {@link Description} objects on the basis of textual representation.  
 *
 */
public class KeyBasedComparator implements Comparator<Description> 
{

	private final String term;

	public KeyBasedComparator(String term)
	{
		this.term = term.toLowerCase();
	}

	/**
	 * Compares two Description objects on the basis of textual representation.
	 * @param o1 
	 * 			 Object of {@link Description}.
	 * @param o2 	
	 * 			 Object of {@link Description}.
	 */
	@Override
	public int compare(Description o1, Description o2) 
	{
		
		String desc1 = o1.getTerm().toLowerCase();
		String desc2 = o2.getTerm().toLowerCase();
		
		int index1 = desc1.indexOf(term);
		int index2 = desc2.indexOf(term);
		
				if((desc1.length() == desc2.length()))
				{
					if(index1 < index2)
						return -1;
					else if(index1 > index2)
						return 1;
					else
						return desc1.compareTo(desc2);
				}
					else if(desc1.length() < desc2.length())
						return -1;
					else if(desc1.length() > desc2.length())
						return 1;
				
			return 0;		
	}
}

