/*
 * NAT - An universal Translator
 * Copyright (C) 2005 Bruno Mascret
 * Contact: bmascret@free.fr
 * 
 * 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.
 * 
 * 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 Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
package nat.convertisseur;

//Package maisons
import nat.Nat;
import gestionnaires.GestionnaireErreur;

//***  java.io ***
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.util.ArrayList;

public class ConvertisseurTexte extends Convertisseur
{
	//Attributs

	protected String sourceEncode;
	protected String sourceEncoding;
	
	//"%", "‰", ponctuation? pourquoi???
	// FEINTE: on remplace ... par … dans ligne lit
	protected String[] ponctuationFin = {"-","”","’",",", ".", ":", ";", "!", "?", "»","…", ")", "]", "}","\""};
	protected String[] ponctuationDebut = {"-","¡","¿","«","“","‘","(", "[", "{","\""};

	public ConvertisseurTexte(String source, String cible)
	{
		super(source, cible);
		sourceEncoding = "UTF-8";
	}
	
	public ConvertisseurTexte(String source, String cible,String sEncoding)
	{
		super(source, cible);
		sourceEncoding = sEncoding;
	}

	public boolean convertir(GestionnaireErreur gest)
	{
		tempsExecution = System.currentTimeMillis();
		boolean retour=true;
		nbCars = 0;
		nbMots = 0;
		nbPhrases = 0;
		try
		{
			gest.AfficheMessage("** Ouverture du fichier source: " + source + " ...",Nat.LOG_VERBEUX);
			//RandomAccessFile raf = new RandomAccessFile(source, "r");
			BufferedReader raf = new BufferedReader(new InputStreamReader(new FileInputStream(source),sourceEncoding));
			gest.AfficheMessage("ok\n** Conversion du fichier source ...",Nat.LOG_NORMAL);
			BufferedWriter fcible = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(cible),"UTF8"));

			//on met les entêtes au fichier xml
			fcible.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
			fcible.write("\n<!DOCTYPE doc:doc SYSTEM \""+DTD +"\">");
			fcible.write("\n<doc:doc xmlns:doc=\"espaceDoc\">");
	
			String ligne;

			ligne =  raf.readLine();
			while ( ligne != null )
			{
				nbPhrases++;
				fcible.write("\n\t<phrase>\n");
				ligneLit(ligne, gest, fcible);
				fcible.write("\n\t</phrase>\n");
				ligne =  raf.readLine();
			}
			fcible.write("\n</doc:doc>");
			fcible.close();
			gest.AfficheMessage("\nLe document contient " + nbPhrases +" paragraphes, " + nbMots + " mots et " + nbCars +" caractères.",Nat.LOG_VERBEUX);
			tempsExecution = System.currentTimeMillis() - tempsExecution;
			gest.AfficheMessage("ok\n----Conversion terminée en " + tempsExecution + " msec.\n",Nat.LOG_SILENCIEUX);
			retour = true;
		}
		catch (java.io.IOException e)
		{
			gest.setException(e);
			gest.GestionErreur();
			retour = false;
		}
		catch (Exception e)  
		{
			gest.setException(e);
			gest.GestionErreur();
			retour = false;
		}		
		return retour;//retour;
	}

	protected void ligneLit(String ligne, GestionnaireErreur gest, BufferedWriter fcible)
	{
		int i=0;
		int j=0;
		String [] mots = null;
		//feinte pour pas s'emmm... avec les points de suspensions et les tab:
		ligne = ligne.replace("...","…");
		ligne = ligne.replace("\t"," ");
		ligne = ligne.replace("\n","");
		ligne = ligne.replace("\u00A0"," "); //espace insécable
		if (ligne != null && ligne.length()>0)
		{
			mots=ligne.split(" ");
			if (mots.length == 0) // si il n'y a qu'un seul mot dans la ligne
			{
				mots = new String[1];
				mots[0] = ligne;
			}
			//System.out.println("ligne:" + ligne + " mot0:" + mots[0]);
		}
		if ((mots != null) && !(mots.length==1 && mots[0] == " "))// changer avec taille split:fait
		{
			try
			{
				fcible.write("\n\t\t<lit>");
				nbMots = nbMots + mots.length;
				while (i<mots.length)
				{
					j=0;
					//boolean trouve=false;
					boolean suivant = false;
					//int debutMot = 0;
					while (j<ponctuationDebut.length)
					{
						if (mots[i].startsWith(ponctuationDebut[j])||mots[i]==ponctuationDebut[j])
						{		//mots[i].length()-1		    	
							fcible.write("\n\t\t\t<ponctuation>" + mots[i].charAt(0) + "</ponctuation>");
							if (mots[i].length()>1)
							{
								mots[i] = mots[i].substring(1,mots[i].length());
								j=0;
							}
							else
							{
							//c'est fini, on passe au mot suivant
								suivant = true;
							}
							nbCars = nbCars + 1;
						}
						j++;
					}
					j=0;
					//trouve = false;
					if(!suivant)
					{
						ArrayList<String> ponctfin=  new ArrayList<String>();
						// on extrait les ponctuations de fin
						while (j<ponctuationFin.length)
						{
							if (mots[i].endsWith(ponctuationFin[j])||mots[i]==ponctuationFin[j])
							{			
								ponctfin.add("\n\t\t\t<ponctuation>" +mots[i].charAt(mots[i].length()-1) + "</ponctuation>");
								mots[i] = mots[i].substring(0,mots[i].length()-1);
								j=0;
							}
							else{j++;}
								/*if (mots[i].length()>1)
								{
									fcible.write("\n\t\t\t<mot>" + mots[i].substring(0,mots[i].length()-1).replace("&","&amp;").replace("<","&lt;") +"</mot>");
								}
								fcible.write("\n\t\t\t<ponctuation>" + mots[i].charAt(mots[i].length()-1) + "</ponctuation>");
								nbCars = nbCars + mots[i].length() + 1;
								trouve=true;*/
						}
						fcible.write("\n\t\t\t<mot>" + mots[i].replace("&","&amp;").replace("<","&lt;") + "</mot>");//\t\t\t<espace></espace>");
						int nbPonct = ponctfin.size();
						nbCars = nbCars + mots[i].length() + nbPonct;
						// on écrit les ponctuations si il y en a
						for(j=nbPonct-1;j>=0;j--){fcible.write(ponctfin.get(j));}	
					}
					i++;
				}
				i=0;
				fcible.write("\n\t\t</lit>\n");
			}
		catch (java.io.IOException e)
			{
			 gest.setException(e);
			 gest.GestionErreur();
			}
		}
	}
	public void toISO()
	{
		BufferedReader br = null;
		PrintWriter pw = null;
		try
		{
			//flux de lecture en UTF-8
			br = new BufferedReader(new InputStreamReader(new FileInputStream(source),"UTF-8"));
			//flux d'écriture en ISO (valeur par défaut)
			pw = new PrintWriter(new FileOutputStream(sourceEncode));
			String ligne;
			while((ligne = br.readLine())!=null)
			{
				pw.println(ligne);
			}
		}
		catch(Exception e){e.printStackTrace();}
		finally
		{
			try { pw.close();} catch( Throwable e ) {}
			try { br.close();} catch( Throwable e ) {}
		}
	}
	/* Methodes d'accès */
	public void setSourceEncoding(String se)
	{
		sourceEncoding = se;
	}
	
}