/*
 * Origine.java, 9 sept. 2005
 * 
 * This file is part of FilmZ.
 *
 * Copyright © 2005 Johan Cwiklinski
 *
 * File :               Origine.java
 * Author's email :     johan@x-tnd.be
 * Author's Website :   http://www.x-tnd.be/
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 */

package be.xtnd.films;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.log4j.Logger;

import be.xtnd.commons.db.Database;
import be.xtnd.gui.FilmzMain;

/**
 * Gère les genres 
 * @author Johan Cwiklinski
 * @version 1.1
 */
public class Origine extends JoinClass{
	/** Nom de la table */
	public static String TABLE = "origines";
	/** Nom de la table genres spéciaux */
	//public static String TABLE_SPECIALS = "spe_"+TABLE;
	/** Nom du champ de clé primaire */
	public static String PK = "id_origine";
	/** Nom du champ de valeur */
	public static String VALUE = "origine";
	/** Nom de la table de jonction avec la table films */
	//public static String JUNCTION_TABLE = FilmzMain.collection.getTable() + "origines"; 
	/** Nom de la table de jonction avec la table films spéciaux */
	//public static String JUNCTION_TABLE_SPECIALS = "spe_"+JUNCTION_TABLE; 
	/** Requête de liste des éléments */
	public static String LIST_QUERY = "SELECT * FROM "+TABLE+" ORDER BY "+VALUE+" ASC";
	/** Tabl relations origines/origines web */
	public static final String WEB_RELATION = "weborigins";
	/** Origine inconnue */
	public static final Integer UNKNOWN = 1;

	/**
	 * Constructeur par défaut
	 */
	public Origine(){
		super(
				Logger.getLogger(Acteur.class.getName()), //logger
				TABLE, //table
				FilmzMain.collection.getTable() + "origines",
				//JUNCTION_TABLE, //table jonction 
				PK, //clé primaire 
				VALUE //nom champ
				);
	}
	
	/**
	 * Initialise un acteur en fonction de son id
	 * @param id id de l'acteur à initialiser
	 */
	public Origine(Integer id) {
		this();
		this.loadFromId(id);
	}
	
	/**
	 * Initialise un acteur en fonction de son nom
	 * @param nom nom de l'acteur à initialiser
	 */
	public Origine(String nom) {
		this();
		this.loadFromValue(nom);
		if(this.id==null)
			this.loadWebRelation(nom);
	}
	
	/**
	 * Tableau d'origines par film
	 * 
	 * @param film : l'identifiant du film
	 * @return Renvoie liste d'origines
	 */
	public static ArrayList<Origine> originesFilm(Integer film){
		logger = Logger.getLogger(Origine.class.getName());
		table = TABLE;
		//table_specials = "spe_"+TABLE;
		pk = PK;
		value = VALUE;
		junction_table = FilmzMain.collection.getTable() + "origines"; //JUNCTION_TABLE;
		//junction_table_specials = "spe_"+junction_table;
		ArrayList<Origine> array = new ArrayList<Origine>(5);
		ArrayList<Integer> refs = jonctionFilm(film);
		for(int i = 0 ; i < refs.size() ; i++){
			array.add(new Origine(refs.get(i)));
		}
		array.trimToSize();
		return array;
	}
	
	/**
	 * Enregistre le tableau d'origines associé au film dans la base
	 * @param f
	 * @return int
	 */
	public int enregistrerOrigines(Film f){
		/*return enregistrerRefs(
				f.getId(),
				(special)?Origine.JUNCTION_TABLE_SPECIALS:Origine.JUNCTION_TABLE,					
				f.getDeletedOrigins(),
				f.getOrigines()
				);*/
		return enregistrerRefs(
				f.getId(),
				FilmzMain.collection.getTable() + "origines",
				//Origine.JUNCTION_TABLE,					
				f.getDeletedOrigins(),
				f.getOrigines()
		);
	}
	
	/**
	 * Cherche une relation existante via le nom donné
	 * @param valeur textuelle de la relation à chercher
	 */
	public void loadWebRelation(String valeur) {
		this.valeur=valeur;
		try {
			ResultSet rs = database.execQuery(
					"SELECT * FROM "+WEB_RELATION+" WHERE web='"+
					Database.replace(valeur,"\'","\\\'")+"'");
			while(rs.next())
				this.id = rs.getInt(pk);
		} catch (SQLException e) {
			e.printStackTrace();
			logger.fatal("SQLException searching web relation : "+e.getMessage()+" (code "+e.getErrorCode()+")");
			sqlMessage = "Message was : "+e.getMessage();
			sqlError = e.getErrorCode();
		}
	}
	
	/**
	 * Crée une relation entre le genre web etg le genre de la base
	 * @param s genre de la base
	 * @return objet origine existante
	 */
	public Origine createRelation(String s){
		Origine existing = new Origine(s);
		String query = "INSERT INTO "+WEB_RELATION+" VALUES ('"+this.getOrigine()+"',"+existing.getId()+")";
		try {
			database.execUpdate(query);
		} catch (SQLException e) {
			e.printStackTrace();
			logger.fatal("SQLException initializing "+value+" by id : "+e.getMessage()+" (code "+e.getErrorCode()+")");
			sqlMessage = "Message was : "+e.getMessage();
			sqlError = e.getErrorCode();
		}
		return existing;
	}
	
	/**
	 * @return nombre d'origines dans la base
	 */
	public Integer getCount(){
		int count = -1;
		try{
			String query = "SELECT count("+PK+") as compte FROM "+TABLE;
			ResultSet rs = database.execQuery(query);
			rs.first();
			count = rs.getInt("compte");
		}catch(SQLException e){
			logger.fatal("SQLException counting origins : "+e.getMessage()+" (code "+e.getErrorCode()+")");
			sqlMessage = "Message was : "+e.getMessage();
			sqlError = e.getErrorCode();
		}
		return count;
	}

	/**
	 * @return Renvoie origine.
	 */
	public String getOrigine() {
		return this.getValeur();
	}
	/**
	 * @param origine origine à définir.
	 */
	public void setOrigine(String origine) {
		this.setValeur(origine);
	}
}
