package org.dspace.newsletter;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

import org.dspace.core.ConfigurationManager;

import org.apache.log4j.Logger;



public class NewsletterIndexer {
  
  private final String fs = System.getProperty("file.separator");
  private String INDEX_DIR = "";
  private String DATA_DIR = "";
  
  private static final Logger log = Logger.getLogger(NewsletterIndexer.class);
  
  public static void main(String [] args){
		if(args!=null && args[0]!= null){
			if(args[0].equals("index-all")){
				NewsletterIndexer indexer = new NewsletterIndexer();
				indexer.indexar();
			}
			if(args[0].equals("index-item") && args[1]!=null){
				String amicus = args[1];
				NewsletterIndexer indexer = new NewsletterIndexer();
				indexer.indexarPublicacion(amicus);
			}
			if(args[0].equals("index-delete-all")){
				NewsletterIndexer indexer = new NewsletterIndexer();
				indexer.borrarPublicaciones();
			}
			if(args[0].equals("index-delete-item")){
				String amicus = args[1];
				NewsletterIndexer indexer = new NewsletterIndexer();
				indexer.borrarPublicacion(amicus);
			}
		}
  }
  
  public NewsletterIndexer(){      
      //INITIALIZE PARAMS
      INDEX_DIR = ConfigurationManager.getProperty("search.extended.dir");
      DATA_DIR  = ConfigurationManager.getProperty("search.extended.data");
  }
  
  
  public NewsletterIndexer(String cmd,String publicacion){      
      //INITIALIZE PARAMS
      INDEX_DIR = ConfigurationManager.getProperty("search.extended.dir");
      DATA_DIR  = ConfigurationManager.getProperty("search.extended.data");
      if(cmd!=null && !cmd.equals("")){	  
			  if( cmd.equals("index-all")){ indexar(); }
			  if( cmd.equals("index-item")){
			      if(publicacion!=null && !publicacion.equals("")){
				  		indexarPublicacion(publicacion);
			      }
			  }
      }
  }
  
  
  public NewsletterIndexer(String index_dir, String data_dir,String cmd,String publicacion){            
      //INITIALIZE PARAMS
      INDEX_DIR=index_dir;
      DATA_DIR =data_dir;
      if(cmd!=null && !cmd.equals("")){	  
			  if( cmd.equals("index-all")){ 
				indexar(); 
			  }
			  if( cmd.equals("index-item")){
				  if(publicacion!=null && !publicacion.equals("")){
				  	indexarPublicacion(publicacion);
				  }
		  	}
      }
  }
  
  
  public int indexar(){
      log.debug("Indexando todo el contenido");
      long start = System.currentTimeMillis();
      int filesIndexed = 0;
      try{
			  File[] files = new File(DATA_DIR).listFiles();  
			  for (File f: files){
			      if(f.isDirectory()){
				  		filesIndexed += indexarPublicacion( f.getName());
			      }
			  }
      }catch(Exception e){
		log.error(e);
      }	    
      long end = System.currentTimeMillis();
      log.info(filesIndexed + " ficheros indexados en " + (end - start) + " milisegundos");
      return filesIndexed;
  }
  
  public void borrarPublicacion(String publicacion){
	File f = new File(INDEX_DIR + fs + publicacion);
	  if(f.exists() && f.isDirectory()){
		  File[] listOfFiles = f.listFiles();
		  for (File aux:listOfFiles) {
			  try{						
				  aux.delete();
			  }catch(Exception e){log.error(e.getMessage());}
		  }
		  f.delete();
	  }
  }
  
  public void borrarPublicaciones(){
	File f = new File(INDEX_DIR);
	  if(f.exists() && f.isDirectory()){
		  File[] listOfFiles = f.listFiles();
		  for (File aux:listOfFiles) {
			  try{						
				  borrarPublicacion(aux.getName());
			  }catch(Exception e){log.error(e.getMessage());}
		  }
	  }
  }
  
  public int indexarPublicacion( String publicacion){
      log.debug("Indexando la publicación: " + publicacion );
      Indexer indexer = null;
      long start = System.currentTimeMillis();
      int filesIndexed = 0;
      try{
		  //SI EXISTE EL OCR
		  File fAux = new File(DATA_DIR + fs + publicacion);
		  if(fAux.exists()){
			//BORRAMOS EL INDICE SI YA EXISTIA
			  File f = new File(INDEX_DIR + fs + publicacion);
			  if(f.exists() && f.isDirectory()){
				  File[] listOfFiles = f.listFiles();
				  for (File aux:listOfFiles) {
					  try{						
						  aux.delete();
					  }catch(Exception e){log.error(e.getMessage());}
				  }
			  }
			  boolean creado = f.mkdir();
			  String analizador = ConfigurationManager.getProperty("search.extended.analyzer.class");
			  indexer = new Indexer(f.getAbsolutePath(),analizador);
		  
			  filesIndexed = indexarRecursivo(DATA_DIR + fs + publicacion, publicacion, indexer);
			  indexer.close();
		  }else{
			log.error("No existe contenido en el fichero");
		  }
      }catch(Exception e){
	  try {
	      indexer.close();
	  }catch (IOException e1) {
	      log.error(e1);
	  }
	  log.error(e);
      }
      long end = System.currentTimeMillis();
      log.info(filesIndexed + " ficheros indexados en " + (end - start) + " milisegundos");
      return filesIndexed;
  }
  
  
  private int indexarRecursivo(String ruta, String namicus,Indexer indexer) throws Exception{		
      int i = 0;
      TextFilesFilter filter = new TextFilesFilter();
      File aux = new File(ruta);
      for (String subcarpeta: aux.list()){
	  File f = new File(ruta + fs + subcarpeta);
	  if(f.isDirectory()){
	      i += indexarRecursivo(ruta + fs + subcarpeta, namicus, indexer);
	  }else if( !f.isHidden() && f.exists() && f.canRead() && (filter == null || filter.accept(f)) ){
	      indexer.indexFile(f);
	      i++;
	  }
      }
      return i;
  }
  
  
  
  
}  
