/*
 * Dvdfr.java, 4 févr. 2006
 * 
 * This file is part of FilmZ.
 *
 * Copyright © 2006 Johan Cwiklinski
 *
 * File :               Dvdfr.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.plugins;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.JOptionPane;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import be.xtnd.commons.MessagesCommons;
import be.xtnd.commons.gui.MainGui;


/**
 * @author Johan Cwiklinski
 *
 */
public class Dvdfr extends RecupWeb{
    
	/**
	 * Cherche le titre en paramètre
	 * sur dvdfr.com
	 * Le résultat de la recherche est un fichier xml
	 * 
	 * @param title titre à chercher
	 */
    public Dvdfr(String title){
		super(
				title, 
				"http://www.dvdfr.com/api/search.php?title=[word]",
				null,
				true
				);
    	
    }

	@Override
	protected void nextPages(StringBuffer data) {
		// unused for this website
	}

	@Override
	protected void parseXmlResults(){
		List dvds = racine.getChildren();
		Iterator i = dvds.iterator();
    	while(i.hasNext()){
			try {
	    		Element courant = (Element)i.next();
	    		listeReponses[current] = new Object[3];
				String rec_title_fr = courant.getChild("titres").getChildText("fr");
				String rec_title_en = courant.getChild("titres").getChildText("vo");
				String rec_alter_fr = courant.getChild("titres").getChildText("alternatif");
				String rec_alter_en = courant.getChild("titres").getChildText("alternatif_vo");
				String rec_edition = courant.getChildText("edition");
				if(!rec_edition.trim().equals("")) rec_edition = " - Édition "+rec_edition;
				XPath real = XPath.newInstance("stars/star[@type='Réalisateur']");
				ArrayList reals = (ArrayList) real.selectNodes(courant);
				StringBuffer rec_reals = new StringBuffer();
				if(reals.size()>0) rec_reals.append(" - Réalisateur(s) : ");
				for(int z = 0 ; z<reals.size() ; z++){
					if(z != reals.size()-1) rec_reals.append(", "); 
					Element el = (Element)reals.get(z);
					rec_reals.append(el.getText());
				}
				
				listeReponses[current][2] = rec_alter_fr+" "+rec_alter_en+rec_edition+rec_reals;
				listeReponses[current][1] = rec_title_fr+" ("+rec_title_en+")";
				listeReponses[current][0] = courant.getChild("id").getText();			        			
	            current++;
			} catch (JDOMException e) {e.printStackTrace();}
    	}
	}
	
	@Override
	protected void parseResults(StringBuffer data) {
		// unused for this website
	}

	@Override
	protected void loadMovie(String value) {
		int gVersion = 6;
		String movieUrl = "http://www.dvdfr.com/api/dvd.php?id=[value]";
		formattedUrl = movieUrl.replace(
				"[value]", 
				encodeUrl(value));

	    SAXBuilder sxb = new SAXBuilder();
	    try{
	    	URL url = new URL ( formattedUrl );
	    	BufferedInputStream  bis = new BufferedInputStream(url.openStream());
	    	InputStreamReader reader = new InputStreamReader(bis, "ISO-8859-1");
			Document doc = sxb.build(reader);
		    Element racine = doc.getRootElement();
		    String generator = racine.getAttributeValue("generator");
		    if (generator.contains("1.3")) gVersion = 3;
		    XPath real, act;
		    ArrayList reals, acts;
		    
		    switch(gVersion){
		    	case 3 :
				    //titre
		    		titre = racine.getChildText("titres_fr");
				    //sous_titre
				    titreOriginal = racine.getChildText("titres_vo");
				    //realisateurs
					real = XPath.newInstance("realisateurs/realisateur");
					reals = (ArrayList) real.selectNodes(racine);
					for(int z = 0 ; z<reals.size() ; z++){
						Element el = (Element)reals.get(z);
						realisateurs.add(el.getText());
					}
					//acteurs
					act = XPath.newInstance("stars/star");
					acts = (ArrayList) act.selectNodes(racine);
					for(int z = 0 ; z < acts.size() ; z++){
						Element el = (Element)acts.get(z);
						acteurs.add(el.getText());
					}
		    		break;
		    	case 6 :
				    //titre
		    		titre = racine.getChild("titres").getChildText("fr");
				    //sous_titre
				    titreOriginal = racine.getChild("titres").getChildText("vo");
				    //realisateurs
					real = XPath.newInstance("stars/star[@type='Réalisateur']");
					reals = (ArrayList) real.selectNodes(racine);
					for(int z = 0 ; z<reals.size() ; z++){
						Element el = (Element)reals.get(z);
						realisateurs.add(el.getText());
					}
					//acteurs
					act = XPath.newInstance("stars/star[@type='Acteur']");
					acts = (ArrayList) act.selectNodes(racine);
					for(int z = 0 ; z<acts.size() ; z++){
						Element el = (Element)acts.get(z);
						acteurs.add(el.getText());
					}
					//année sortie
					anneeSortie = new Integer(racine.getChildText("sortie").substring(0,3));
		    		break;
		    }
			//origines
			XPath orig = XPath.newInstance("listePays/pays");
			ArrayList origs = (ArrayList) orig.selectNodes(racine);
			for(int z = 0 ; z<origs.size() ; z++){
				Element el = (Element)origs.get(z);
				origines.add(el.getText());
			}
			//genres
			XPath gen = XPath.newInstance("categories/categorie");
			ArrayList gens = (ArrayList) gen.selectNodes(racine);
			for(int z = 0 ; z<gens.size() ; z++){
				Element el = (Element)gens.get(z);
				genres.add(el.getText());
			}
			//durée
			String rec_duree = racine.getChildText("duree");
			if(!rec_duree.trim().equals(""))
				duree = new Integer(rec_duree);
			//année de production
			anneeProduction = new Integer(racine.getChildText("annee"));
			//synopsis
			synopsis = racine.getChildText("synopsis");
		} catch (JDOMException e) {e.printStackTrace();
		} catch (UnknownHostException e1){
			listeReponses = new Object[1][];
			listeReponses[0] = new Object[]{"","Erreur de connexion au site web"};
	    	JOptionPane.showMessageDialog(
	    			MainGui.desktop,
					MessagesCommons.getString("window.messages.unknownhost"),
					MessagesCommons.getString("window.messages.error"),
					JOptionPane.ERROR_MESSAGE
	    	);				
		} catch (IOException e) {e.printStackTrace();}

	}

	@Override
	protected void loadActors(String url) {
	}
}
