/*
 * CreateEuropeanaMetadata.java
 *
 */
package org.dspace.administer;

import java.sql.SQLException;

import org.dspace.authorize.AuthorizeException;
import org.dspace.core.Context;
import org.dspace.content.DCValue;
import org.dspace.content.Item;
import org.dspace.content.ItemIterator;
import org.dspace.content.Community;
import java.io.File;
import org.dspace.core.ConfigurationManager;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import org.dspace.storage.rdbms.DatabaseManager;

public class CreateEuropeanaMetadata
{
	
	private static String type = "TEXT";
	private static String provider = "Liburuklik: Euskal Liburutegi Digitala";
	private static String url = "";
	private static String identifier = "";
	private static String rights = "http://creativecommons.org/publicdomain/zero/1.0/";
	private static String thumb_path = "http://www.liburuklik.euskadi.eus/applet/libros/JPG/";
	private static String updated = "";
	
    /**
     * For invoking via the command line.
     * 
     * @param argv
     *            command-line arguments
     */
    public static void main(String[] argv)
    	throws Exception
    {
    	
    	Context c = new Context();
    	c.setIgnoreAuthorization(true);
        // Get all items
      int count = 0;
      int count_ondarenet = 0;
      
      int ondarenetId = getOndarenetId();
      int hemerotecaId = getHemerotecaId();
      
      
    	ItemIterator allItems = Item.findAll(c);
    	while (allItems.hasNext()) {

    			updated = "";
          Item myItem = allItems.next();
          
          if ((!perteneceAOndarenet(myItem, ondarenetId)) && (!perteneceAHemeroteca(myItem, hemerotecaId))) {
	          LoadEuropeanaMetadata(c, myItem);
	          if (!updated.equals("")) {
	          	count++;
	          	System.out.println("  Item modificado: " + updated);
	          	c.commit();
	          }
	        }
	        else {
	        	count_ondarenet++;
	        }
    	}
    	c.complete();
    	
    	System.out.println("Finalizado: " + count + " registros.");
    	System.out.println("Finalizado: " + count_ondarenet + " registros ondarenet.");
    }
    
    private static void LoadEuropeanaMetadata(Context c, Item item) throws SQLException, AuthorizeException {
    	DCValue[] allDC = item.getDC(Item.ANY, Item.ANY, Item.ANY);
    	for (int i = 0; i < allDC.length; i++) {
    		if ((allDC[i].element.equals("identifier")) &&
    			(allDC[i].qualifier != null) && (allDC[i].qualifier.equals("uri"))) {
    				url = allDC[i].value;
    				url = url.replace("http://hdl.handle.net/","http://www.liburuklik.euskadi.eus/handle/");
    		}
    			
    		
    		if ((allDC[i].element.equals("identifier")) &&
        			(allDC[i].qualifier == null)) identifier = allDC[i].value;
    	}
    	LoadDataProvider(c, item);
    	LoadUrl(c, item);
    	LoadObject(c, item);
    	LoadProvider(c, item);
    	LoadRights(c, item);
    	LoadType(c, item);
    	LoadUnstored(c, item);
    	item.update();
    }
    
    //TIENEN QUE EXISTIR LAS ETIQUETAS DE LOS METADATOS EN DSPACE
    
    //europeana.dataProvider
    private static void LoadDataProvider(Context c, Item item) throws SQLException, AuthorizeException {
    	String value = "";
    	DCValue[] eu_dataProvider = item.getMetadata("europeana", "dataProvider", Item.ANY, Item.ANY);
    	for (int i = 0; i < eu_dataProvider.length; i++) value = eu_dataProvider[i].value;
    	if (!provider.equals(value)) {
    		item.clearMetadata("europeana", "dataProvider", Item.ANY, Item.ANY);
    		item.addMetadata("europeana", "dataProvider", null, null, provider);
    		updated = identifier;
    	}
    }
    
    //europeana.isShownAt
    private static void LoadUrl(Context c, Item item) throws SQLException, AuthorizeException {
    	String value = "";
    	DCValue[] eu_isShownAt = item.getMetadata("europeana", "isShownAt", Item.ANY, Item.ANY);
    	for (int i = 0; i < eu_isShownAt.length; i++) value = eu_isShownAt[i].value;
    	if (!url.equals(value)) {
    		item.clearMetadata("europeana", "isShownAt", Item.ANY, Item.ANY);
    		item.addMetadata("europeana", "isShownAt", null, null, url);
    		updated = identifier;
    	}
    }
    
    //europeana.object
    private static void LoadObject(Context c, Item item) throws SQLException, AuthorizeException {
    	if ((item == null) || (item.getOwningCollection() == null)) return;
    	String collection_name = (item.getOwningCollection()).getName();
    	
    	
    	String fs = System.getProperty("file.separator");
	
		  
    	//PARA LOS REGISTROS CON IMAGENES EN FORMATO GIF  
		  String extensionIMG = "jpg";
		  String format = "";
		  DCValue[] dc_format = item.getDC("format", null, Item.ANY);
		  if (dc_format != null) {
				if (dc_format.length != 0) format = dc_format[0].value;
	    	if (format.contains("GIF")) extensionIMG = "gif";
	    }
    	
    	String itemFolder = item.getFileSystem();
    	
    	String thumb = thumb_path + itemFolder + "/" + identifier + "/thumb_europeana/" + identifier + "." + extensionIMG;
    	String value = "";
    	DCValue[] eu_object = item.getMetadata("europeana", "object", Item.ANY, Item.ANY);
    	for (int i = 0; i < eu_object.length; i++) value = eu_object[i].value;
    	if (!thumb.equals(value)) {
    		item.clearMetadata("europeana", "object", Item.ANY, Item.ANY);
    		item.addMetadata("europeana", "object", null, null, thumb);
    		updated = identifier;
    	}
    }
    
    //europeana.provider
    private static void LoadProvider(Context c, Item item) throws SQLException, AuthorizeException {
    	String value = "";
    	DCValue[] eu_provider = item.getMetadata("europeana", "provider", Item.ANY, Item.ANY);
    	for (int i = 0; i < eu_provider.length; i++) value = eu_provider[i].value;
    	if (!provider.equals(value)) {
    		item.clearMetadata("europeana", "provider", Item.ANY, Item.ANY);
    		item.addMetadata("europeana", "provider", null, null, provider);
    		updated = identifier;
    	}
    }
    
    //europeana.rights
    private static void LoadRights(Context c, Item item) throws SQLException, AuthorizeException {
    	String value = "";
    	DCValue[] eu_rights = item.getMetadata("europeana", "rights", Item.ANY, Item.ANY);
    	for (int i = 0; i < eu_rights.length; i++) value = eu_rights[i].value;
    	if (!rights.equals(value)) {
    		item.clearMetadata("europeana", "rights", Item.ANY, Item.ANY);
    		item.addMetadata("europeana", "rights", null, null, rights);
    		updated = identifier;
    	}
    }
    
    
    //europeana.type
    private static void LoadType(Context c, Item item) throws SQLException, AuthorizeException {
    	if ((item == null) || (item.getOwningCollection() == null)) return;
    	String collection_name = (item.getOwningCollection()).getName();
    	if (collection_name.endsWith("@BM_IKUST_ALAIA_FOTOGRAFIAS")) type = "IMAGE";
    	else                                                         type = "TEXT";
    	String value = "";
    	DCValue[] eu_type = item.getMetadata("europeana", "type", Item.ANY, Item.ANY);
    	for (int i = 0; i < eu_type.length; i++) value = eu_type[i].value;
    	if (!type.equals(value)) {
    		item.clearMetadata("europeana", "type", Item.ANY, Item.ANY);
    		item.addMetadata("europeana", "type", null, null, type);
    		updated = identifier;
    	}
    }
    
    
    //europeana.unstored
    private static void LoadUnstored(Context c, Item item) throws SQLException, AuthorizeException {
    	String value = "";
    	DCValue[] eu_unstored = item.getMetadata("europeana", "unstored", Item.ANY, Item.ANY);
    	for (int i = 0; i < eu_unstored.length; i++) value = eu_unstored[i].value;
    	if ((value != null) && (!value.equals(""))) {
    		item.clearMetadata("europeana", "unstored", Item.ANY, Item.ANY);
    		item.addMetadata("europeana", "unstored", null, null, "");
    		updated = identifier;
    	}
    }
    
    
    //Cambio para GV. Metodo para ver si un item pertenece a Ondarenet
    public static boolean perteneceAOndarenet(Item i, int identificador_ondarenet) throws SQLException, AuthorizeException {
    	if ((i == null) || (i.getOwningCollection() == null)) return true;
			Community[] listaCommunities = i.getOwningCollection().getCommunities();
			for(Community c : listaCommunities){
				if(c.getID() == identificador_ondarenet) return true;
			}
			return false;
		}
		
		
		//Cambio para GV. Metodo para ver si un item pertenece a Ondarenet
    public static int getOndarenetId() throws SQLException, AuthorizeException {
    	PreparedStatement ps = null;
    	ResultSet rs = null;
    	int ondarenetId = -1;
			try {
			  Connection connection = DatabaseManager.getConnection();
				String consulta = "SELECT COMMUNITY_ID FROM COMMUNITY WHERE SHORT_DESCRIPTION = 'ONDARENET'"; 
				ps = connection.prepareStatement(consulta);
				rs = ps.executeQuery();
				if(rs.next()) ondarenetId = rs.getInt("COMMUNITY_ID");
			}
			catch(SQLException e) { e.printStackTrace(); }
			finally {
				rs.close();
				ps.close();
			}
			return ondarenetId;
		}
		
		//Cambio para GV. Metodo para ver si un item pertenece a Ondarenet
    public static boolean perteneceAHemeroteca(Item i, int identificador_hemeroteca) throws SQLException, AuthorizeException {
    	if ((i == null) || (i.getOwningCollection() == null)) return true;
			Community[] listaCommunities = i.getOwningCollection().getCommunities();
			for(Community c : listaCommunities){
				if(c.getID() == identificador_hemeroteca) return true;
			}
			return false;
		}
		
		//Cambio para GV. Metodo para ver si un item pertenece a Hemeroteca
    public static int getHemerotecaId() throws SQLException, AuthorizeException {
    	PreparedStatement ps = null;
    	ResultSet rs = null;
    	int ondarenetId = -1;
			try {
			  Connection connection = DatabaseManager.getConnection();
				String consulta = "SELECT COMMUNITY_ID FROM COMMUNITY WHERE SHORT_DESCRIPTION = 'HEMEROTECA'"; 
				ps = connection.prepareStatement(consulta);
				rs = ps.executeQuery();
				if(rs.next()) ondarenetId = rs.getInt("COMMUNITY_ID");
			}
			catch(SQLException e) { e.printStackTrace(); }
			finally {
				rs.close();
				ps.close();
			}
			return ondarenetId;
		}
		
    
}
