/*
 * 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;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import nat.ConfigNat;

import joptsimple.OptionSet;
import joptsimple.OptionException;

import gestionnaires.GestionnaireErreur;
import ui.FenetrePrinc;

public class Nat 
{
    //constantes
    public final static int LOG_SILENCIEUX = 1;
    public final static int LOG_NORMAL = 2;
    public final static int LOG_VERBEUX = 3;
    public final static int LOG_DEBUG = 4;
	public static boolean Saxon = false;
   
    //fichier de configuration par defaut
    //private String fichierConf = "configurations/defaut.cfg";
    //private ConfigNat conf;
	
    private static String licence;

	
    private Transcription transcription = null;
	
    public Nat() 
    {
	licence = getLicence("","");
	/*
	  getLastConf();
	  licence = getLicence("","");
	  conf = ConfigNat.Charger(fichierConf);
	  if (conf==null){conf = new ConfigNat(fichierConf);}
	*/
    }

    /* méthodes d'accès */
	
    //public void setFichierConf(String f){fichierConf = f;}
    public String getFichierConf(){return ConfigNat.getCurrentConfig().getFichierConf();}	
	
    public String getVersionLong(){return ConfigNat.getCurrentConfig().getVersionLong();};
    public String getVersion(){return ConfigNat.getCurrentConfig().getVersion();};
	
    //public ConfigNat getConf(){return conf;}
    /*
     * Modifie la configuration en cours;
     * Change le contenu du fichier last.conf pour lui donner le nom du nouveau fichier de conf
     * @exception IOException Erreur E/S lors de l'écriture du fichier last.conf
     * @exception UnsupportedEncodingException Encoding UTF8 non supporté
     * @exception FileNotFoundException fichier last.conf non trouvé
     */
    /*public void setConf(ConfigNat cfg)
    {//TODO à virer
	//conf = cfg;
	fichierConf = ConfigNat.getCurrentConfig().getFichierConf();
	//écriture du nom du fichier de conf en cours
	BufferedWriter bw;
	try 
	    {
		bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("last.conf"),"UTF-8"));
		bw.write(fichierConf);
		bw.close();
	    }
	catch (UnsupportedEncodingException uee){uee.printStackTrace();}
	catch (FileNotFoundException fnfe){fnfe.printStackTrace();} 
	catch (IOException ioe){ioe.printStackTrace();}
    } */

    //public String getLicence(){return licence;}
	
    public static String getLicence(String prefixe, String suffixe)
    {
	licence =  prefixe + " * NAT - An universal Translator\n" +
	    "* Copyright (C) 2005 Bruno Mascret\n" +
	    "* Contact: bmascret@free.fr\n" +
	    "* \n" +
	    "* This program is free software; you can redistribute it and/or\n" +
	    "* modify it under the terms of the GNU General Public License\n" +
	    "* as published by the Free Software Foundation; either version 2\n" +
	    "* of the License.\n" +
	    "* \n" +
	    "* This program is distributed in the hope that it will be useful,\n" +
	    "* but WITHOUT ANY WARRANTY; without even the implied warranty of\n" +
	    "* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n" +
	    "* GNU General Public License for more details.\n" +
	    "* \n" +
	    "* You should have received a copy of the GNU General Public License\n" +
	    "* along with this program; if not, write to the Free Software\n" +
	    "* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.\n" +
	    suffixe;	
	return licence;
    }
    
    /**
     * Récupère le nom du dernier fichier de configuration utilisé (stocké dans le fichier last.conf de la racine)
     * Si une erreur se produit, on ne change pas la valeur par défaut de fichierConf
     * @exception IOException Erreur E/S lors de la lecture du fichier last.conf
     * @exception UnsupportedEncodingException Encoding UTF8 non supporté
     * @exception FileNotFoundException fichier last.conf non trouvé
     */

    
    /*private void getLastConf() 
    {
	String f;
	try
	    {
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("last.conf"),"UTF-8"));
		f = br.readLine();
		fichierConf = f;
		br.close();
	    } 
	catch (UnsupportedEncodingException uee)
	    {
		uee.printStackTrace();
	    }
	catch (FileNotFoundException fnfe)
	    {
		fnfe.printStackTrace();
	    } catch (IOException ioe)
	    {			
		ioe.printStackTrace();
	    }
    }*/

    public boolean fabriqueTranscription(String source, String cible, GestionnaireErreur gest)
    {
	boolean retour = false;
	
		
	transcription = Transcription.fabriqueTranscription(source,cible,gest);
	if(transcription!=null){retour = true;}
	return retour;
    }

    public void lanceScenario()
    {
	transcription.transcrire();
    }

    public String trouveEncodingSource(String source, GestionnaireErreur gest){return Transcription.trouveEncodingSource(source, gest);}
	
    /*
      public Transcription donneTranscription()
      {
      return transcription;
      }
    */

    public static void loadCliOptions(OptionSet options){
	
	ConfigNat cc = ConfigNat.getCurrentConfig();

	String nom = OptNames.ge_log_verbosity;
	if (options.has(nom)){cc.setNiveauLog(((Integer) options.valueOf(nom)).intValue());}

	nom = OptNames.fi_braille_table;
	if (options.has(nom)){cc.setTableBraille(((String) options.valueOf(nom)));}
	
	nom = OptNames.fi_math_transcribe;
	if (options.has(nom)){cc.setTraiterMaths(((Boolean) options.valueOf(nom)).booleanValue());}

	nom = OptNames.fi_math_use_trigo_spec;
	if (options.has(nom)){cc.setMathTrigoSpec(((Boolean) options.valueOf(nom)).booleanValue());}
	
	nom = OptNames.fi_litt_transcribe;
	if (options.has(nom)){cc.setTraiterLiteraire(((Boolean) options.valueOf(nom)).booleanValue());}

	nom = OptNames.fi_litt_abbreg;
	if (options.has(nom)){cc.setAbreger(((Boolean) options.valueOf(nom)).booleanValue());}

	nom = OptNames.fi_music_transcribe;
	if (options.has(nom)){cc.setTraiterMusique(((Boolean) options.valueOf(nom)).booleanValue());}

	nom = OptNames.fi_hyphenation;
	if (options.has(nom)){cc.setCoupure(((Boolean) options.valueOf(nom)).booleanValue());}

	nom = OptNames.fi_hyphenation_dirty;
	if  (options.has(nom)){cc.setModeCoupureSagouin(((Boolean) options.valueOf(nom)).booleanValue());}

	nom = OptNames.fi_line_lenght;
	if (options.has(nom)){cc.setLongueurLigne(((Integer) options.valueOf(nom)).intValue());}
	
	nom = OptNames.en_in;
	if (options.has(nom)){cc.setSourceEncoding((String)options.valueOf(nom));}

	nom = OptNames.en_out;
	if (options.has(nom)){cc.setSortieEncoding((String)options.valueOf(nom));}


    }

    public static void main (String argv [])
    {
    	//System.setProperty("file.encoding","UTF-8");
    	Nat nat = new Nat();
    
    	OptionParserNat parser = new OptionParserNat();
    	try
	    {
    		OptionSet options = parser.parse( argv );
    		if (options.has("gui"))
		    {
			//nat.setConf(ConfigNat.Charger(null));
    			ConfigNat.charger(null);
		    
			FenetrePrinc fenetre = new FenetrePrinc(nat);//convertisseur, transcodeur, nat);
						
			// quoi ?
			// fenetre.setFiltre(nat.getConf().getXSL());
			
			fenetre.pack();
			fenetre.setVisible(true);
		    }
    		else if (options.has("f") && options.has("t"))
		    {
			if (options.has("c")) { 
			    ConfigNat.charger(options.argumentOf( "c" ));
			}
			
			loadCliOptions(options);

    			String cl_from = options.argumentOf( "f" );
    			String cl_to = options.argumentOf( "t" );
    			System.out.println( "conversion de "+cl_from+" vers "+cl_to);
    			//String cl_conf_file;
    			
			//	if (options.has("c")){nat.fichierConf = options.argumentOf( "c" );}
    			//else {nat.fichierConf = "configurations/defaut.cfg";}
			//    			else{nat.getLastConf();}
    			
    			//nat.conf = ConfigNat.Charger(nat.fichierConf);
			//    			ConfigNat.Charger(nat.fichierConf);
    			GestionnaireErreur gestErreur = new GestionnaireErreur(null,null,ConfigNat.getCurrentConfig().getNiveauLog());
    			
    			if (nat.fabriqueTranscription(cl_from, cl_to, gestErreur)){nat.lanceScenario();}
		    }
    		else 
		    {
			parser.printCliUsage();
		    }
	    }
    	catch (OptionException ex)
	    {
    		System.err.println( "====" );
    		System.out.println("Problème dans la ligne de commande");
    		// parser.printHelpOn( System.err );
    		// System.err.println( "====" );
    		// System.err.println( ex.getMessage() );
    		parser.printCliUsage();
	    }
    }
}
