package Detectors;
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

import org.eposoft.jccd.data.JCCDFile;
import org.eposoft.jccd.data.SourceUnitManager;
import org.eposoft.jccd.detectors.APipeline;
import org.eposoft.jccd.detectors.ASTDetector;
import org.eposoft.jccd.preprocessors.APreprocessor;
import org.eposoft.jccd.preprocessors.java.GeneralizeMethodDeclarationNames;
import org.eposoft.jccd.preprocessors.java.GeneralizeVariableNames;

class comparate implements Comparator<String>
{
	@Override
	public int compare(String o1, String o2) {
		
		return o1.compareToIgnoreCase(o2);
		
		
		// TODO Auto-generated method stub
		
	}	
}

public class UnitMap {
	
	public static Map<String,SourceUnitManager> exixtingmap = new TreeMap<String,SourceUnitManager>(new comparate()); 
	
	
	public static SourceUnitManager getUnit(String name)
	{   
		//exixtingmap.
		//System.out.println("Cache Size "+exixtingmap.size()+"mem: "+Runtime.getRuntime().freeMemory()+"===============");
		SourceUnitManager  Unit=exixtingmap.get(name);
	    
	  if(Unit!=null)
	  return Unit;
	  
	  
	  APipeline detector = new ASTDetector();
		JCCDFile[] files1 = { new JCCDFile(name) };
		
		detector.setSourceFiles(files1);
		detector.addOperator(new GeneralizeMethodDeclarationNames());
	      detector.addOperator(new GeneralizeVariableNames()); 
	      Unit = detector.parse(files1);
	      APreprocessor[] preprocessors = detector.getPreprocessors();
	      Unit = detector.preprocess(preprocessors, Unit);
	   if(Runtime.getRuntime().freeMemory()<8104608L) return Unit;
	    
	    try{ 
	    	
	    	exixtingmap.put(name, Unit);
	       
	    }catch (Exception e)
	    {
	    	
	    }
	      return  Unit;
	}
	       
	public static SourceUnitManager upDate(String name)
	{SourceUnitManager  Unit=exixtingmap.get(name);
    
	  if(Unit!=null)
		  exixtingmap.remove(name);
	  return getUnit(name);
}
}


