package com.k_int.aggregator.dpp.util;

import com.k_int.aggregator.dpp.actions.admin.DTOReindexThread;
import org.hibernate.SessionFactory;

import com.k_int.aggregator.repository.RepositoryStoreOptions;
import com.k_int.aggregator.util.SOLRHelper;
import com.k_int.discover.service.dtoHandler.DTODocumentHandlerFactory;
import java.util.ArrayList;
import java.util.List;

/**
 * A class to provide reprocessing functionality to the different edit classes
 * 
 * @author rpb rich@k-int.com
 * @version 1.0 19.11.09
 */
public class ProcessingUtils {

	
        public static int reindexFollowingEdit(SessionFactory sf, DTODocumentHandlerFactory dtoFactory, Long resource, SOLRHelper solrHelper) {
		int numSuccessful = 0;
		
		List<Long> idsToReindex = new ArrayList<Long>();
		idsToReindex.add(resource);
		
		numSuccessful = reindexFollowingEdit(sf, dtoFactory, idsToReindex, solrHelper);
		
		return numSuccessful;

	}
	
	public static int reindexFollowingEdit(SessionFactory sf, DTODocumentHandlerFactory dtoFactory, List<Long> resources, SOLRHelper solrHelper) {
		int numSuccessful = 0;
		
		if ( resources != null ) {
			
			Long[] idsToReindex = resources.toArray(new Long[]{});
			
			Long reindexOptions = RepositoryStoreOptions.REPO_STORE_OPTIONS_CACHE_THUMBNAIL | RepositoryStoreOptions.REPO_STORE_OPTIONS_DO_NOT_PERFORM_DATA_AUGMENTATION;
			
                        DTOReindexThread reindexRunnable = new DTOReindexThread(idsToReindex, reindexOptions, solrHelper, sf, "DTOReindexThread-default", dtoFactory);
			Thread reindexThread = new Thread(reindexRunnable);
			reindexThread.start();

			  try {
				  reindexThread.join();
				  numSuccessful = reindexRunnable.numProcessed - reindexRunnable.numErrors;
				  
			  } catch(InterruptedException ie) {
				  ie.printStackTrace();
				  // TODO - do something with this error...
			  }

			  // Clear up and free memory
			  reindexThread = null;
			  reindexRunnable = null;
		}	
		
		return numSuccessful;
		
	}

}
