/*
Copyright 2012-2014 Samuel Gesche

This file is part of the Greek Reuse Toolkit.

The Greek Reuse Toolkit 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 3 of the License, or
(at your option) any later version.

The Greek Reuse Toolkit 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 the Greek Reuse Toolkit.  If not, see <http://www.gnu.org/licenses/>.
*/

package fr.cnrs.liris.drim.grt.ihm;

import fr.cnrs.liris.drim.grt.ihm.exceptions.InteractionRefuseeException;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Toolkit;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import javax.swing.text.BadLocationException;
import fr.cnrs.liris.drim.grt.modele.Passage;
import fr.cnrs.liris.drim.grt.modele.convertisseurs.ConvertisseurUnicodeVersBetaCode;
import fr.cnrs.liris.drim.grt.modele.convertisseurs.ConvertisseurUnicodeVersBibleWorks;
import fr.cnrs.liris.drim.grt.modele.convertisseurs.ConvertisseurUnicodeVersFormeNormale;
import fr.cnrs.liris.drim.grt.modele.convertisseurs.ConvertisseurUnicodeVersMinuscules;
import fr.cnrs.liris.drim.grt.modele.convertisseurs.ConvertisseurUnicodeVersSansAccentNiEsprit;
import fr.cnrs.liris.drim.grt.proc.parsers.ImportFichier;

/**
 *
 * @author sgesche
 */
public class FenetreCodec extends javax.swing.JFrame {

    private Passage lu;
    
    /**
     * Creates new form FenetreCodec
     */
    public FenetreCodec() {
        initComponents();
        Font grec = new Font("GFS DidotClassic", Font.PLAIN, 16);
        try {
            grec = Font.createFont(Font.TRUETYPE_FONT, new File("GFSDidot-Regular.ttf")).deriveFont(Font.PLAIN, 16f);
        } catch (FontFormatException | IOException ex) {
            lStatut.setText(ex.getClass() + " : " + ex.getMessage());
        }
        tEntree.setFont(grec);
        tEntree.setContentType("text/plain");
        tSortie.setFont(grec);
        tSortie.setContentType("text/plain");
        setSize(Toolkit.getDefaultToolkit().getScreenSize());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel7 = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jPanel9 = new javax.swing.JPanel();
        jPanel10 = new javax.swing.JPanel();
        bRemarques = new javax.swing.JButton();
        jPanel11 = new javax.swing.JPanel();
        bFAQ = new javax.swing.JButton();
        jPanel6 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        tTexteCharge = new javax.swing.JTextField();
        bChargerTexte = new javax.swing.JButton();
        lStatut = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tEntree = new javax.swing.JEditorPane();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        cbFormats = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        tSortie = new javax.swing.JEditorPane();
        jPanel5 = new javax.swing.JPanel();
        bSaveAs = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Greek Reuse Toolkit - Transcodeur");
        getContentPane().setLayout(new java.awt.BorderLayout(10, 10));

        jPanel7.setLayout(new java.awt.BorderLayout());

        jPanel8.setLayout(new java.awt.GridLayout(1, 0));

        jLabel3.setText("<html>\n<p>Bienvenue dans le transcodeur de Greek Quotation Toolkit. Cette application vous permet de changer l'encodage d'un texte en grec ancien, ou d'en supprimer les flexions.</p>\n<p>Vous pouvez charger un fichier ci-dessous ; il sera transformé en unicode. Puis, vous pouvez choisir un nouveau format  plus bas. L'application vous donnera le texte dans le nouvel encodage, et vous pourrez le sauvegarder.</p>\n<p>Vous pouvez également copier du texte en unicode dans la zone de texte, mais cela risque de poser problème si certains caractères sont utilisés (charger le fichier donne lieu à une normalisation au niveau de ces caractères). Il vaut mieux dans ce cas charger ce texte à partir d'un fichier.</p>\n</html>");
        jPanel8.add(jLabel3);

        jPanel7.add(jPanel8, java.awt.BorderLayout.CENTER);

        jPanel9.setLayout(new java.awt.GridLayout(2, 1));

        bRemarques.setText("Mes remarques");
        bRemarques.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bRemarquesActionPerformed(evt);
            }
        });
        jPanel10.add(bRemarques);

        jPanel9.add(jPanel10);

        bFAQ.setText("FAQ");
        jPanel11.add(bFAQ);

        jPanel9.add(jPanel11);

        jPanel7.add(jPanel9, java.awt.BorderLayout.EAST);

        getContentPane().add(jPanel7, java.awt.BorderLayout.PAGE_START);

        jPanel6.setLayout(new java.awt.GridLayout(2, 1));

        jPanel4.setLayout(new java.awt.BorderLayout());

        jLabel1.setText("Fichier à charger : ");
        jPanel1.add(jLabel1);

        tTexteCharge.setColumns(50);
        tTexteCharge.setEnabled(false);
        jPanel1.add(tTexteCharge);

        bChargerTexte.setText("...");
        bChargerTexte.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bChargerTexteActionPerformed(evt);
            }
        });
        jPanel1.add(bChargerTexte);
        jPanel1.add(lStatut);

        jPanel4.add(jPanel1, java.awt.BorderLayout.PAGE_START);

        tEntree.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tEntreeKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(tEntree);

        jPanel4.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel6.add(jPanel4);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jLabel2.setText("Format de sortie : ");
        jPanel3.add(jLabel2);

        cbFormats.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "BibleWorks", "BetaCode", "Unicode", "Unicode en minuscules", "Unicode sans accents ni esprits", "Unicode normalisé" }));
        cbFormats.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbFormatsActionPerformed(evt);
            }
        });
        jPanel3.add(cbFormats);

        jPanel2.add(jPanel3, java.awt.BorderLayout.NORTH);

        tSortie.setEditable(false);
        jScrollPane2.setViewportView(tSortie);

        jPanel2.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        bSaveAs.setText("Enregistrer sous...");
        bSaveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bSaveAsActionPerformed(evt);
            }
        });
        jPanel5.add(bSaveAs);

        jPanel2.add(jPanel5, java.awt.BorderLayout.PAGE_END);

        jPanel6.add(jPanel2);

        getContentPane().add(jPanel6, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bChargerTexteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bChargerTexteActionPerformed
        // TODO add your handling code here:
        String consigne = "Veuillez choisir un texte grec.";
        String[] extensions = new String[]{"rtf", "txt"};
        String[] descriptions = new String[]{"fichier du tlg en unicode (.rtf)", "fichier de bibleworks (.txt)"};
        try {
            File fichier = Demandes.demandeFichier(consigne, extensions, descriptions);
            lStatut.setText("Lecture en cours");
            if(fichier.getName().endsWith(".rtf")) {
                try {
                    lu = ImportFichier.importPatristiqueRTF(fichier);
                    tEntree.setText(lu.getTexteCompletMisEnForme());
                    tTexteCharge.setText(fichier.getAbsolutePath());
                    rafraichisSortie();
                } catch(IOException | BadLocationException ioe) {
                    lStatut.setText(ioe.getClass() + " - " + ioe.getMessage());
                }
            } else if(fichier.getName().endsWith(".txt")) {
                try {
                    lu = ImportFichier.importTexteOuMorphoTXT(fichier);
                    tEntree.setText(lu.getTexteCompletMisEnForme());
                    tTexteCharge.setText(fichier.getAbsolutePath());
                    rafraichisSortie();
                } catch(IOException ioe) {
                    lStatut.setText(ioe.getClass() + " - " + ioe.getMessage());
                }
            }
        } catch(InteractionRefuseeException ire) {
            
        }
    }//GEN-LAST:event_bChargerTexteActionPerformed

    private void cbFormatsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbFormatsActionPerformed
        // TODO add your handling code here:
        rafraichisSortie();
    }//GEN-LAST:event_cbFormatsActionPerformed

    private void bSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bSaveAsActionPerformed
        try {
            // TODO add your handling code here:
            File fichierSauvegarde = Demandes.demandeFichierDestination("Veuillez choisir une fichier où enregistrer.");
            lStatut.setText("Enregistrement en cours.");
            BufferedWriter writer = null;
            try {
                String aExporter = tSortie.getText();
                writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fichierSauvegarde), "UTF-8"));
                writer.write(aExporter);
                writer.flush();
                lStatut.setText("");
            } catch (IOException ioe) {
                lStatut.setText(ioe.getClass() + " - " + ioe.getMessage());
            } finally {
                try {
                    writer.close();
                } catch (IOException ex) {
                    
                }
            }
        } catch (InteractionRefuseeException ex) {
            
        }
        
    }//GEN-LAST:event_bSaveAsActionPerformed

    private void tEntreeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tEntreeKeyPressed
        // TODO add your handling code here:
        rafraichisSortie();
    }//GEN-LAST:event_tEntreeKeyPressed

    private void bRemarquesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bRemarquesActionPerformed
        // TODO add your handling code here:
        new FenetreRemarques().setVisible(true);
    }//GEN-LAST:event_bRemarquesActionPerformed

    private void rafraichisSortie() {
        lStatut.setText("Conversion en cours");
        tSortie.setText("");
        switch (cbFormats.getSelectedItem().toString()) {
            case "BibleWorks":
                tSortie.setText(ConvertisseurUnicodeVersBibleWorks.conversion(tEntree.getText()));
                break;
            case "BetaCode":
                tSortie.setText(ConvertisseurUnicodeVersBetaCode.conversion(tEntree.getText()));
                break;
            case "Unicode":
                tSortie.setText(tEntree.getText());
                break;
            case "Unicode en minuscules":
                tSortie.setText(ConvertisseurUnicodeVersMinuscules.conversion(tEntree.getText()));
                break;
            case "Unicode sans accents ni esprits":
                tSortie.setText(ConvertisseurUnicodeVersSansAccentNiEsprit.conversion(tEntree.getText()));
                break;
            case "Unicode normalisé":
                tSortie.setText(ConvertisseurUnicodeVersFormeNormale.conversion(tEntree.getText()));
                break;
        }
        lStatut.setText("");
    }


    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FenetreCodec.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FenetreCodec.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FenetreCodec.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FenetreCodec.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FenetreCodec().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bChargerTexte;
    private javax.swing.JButton bFAQ;
    private javax.swing.JButton bRemarques;
    private javax.swing.JButton bSaveAs;
    private javax.swing.JComboBox cbFormats;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lStatut;
    private javax.swing.JEditorPane tEntree;
    private javax.swing.JEditorPane tSortie;
    private javax.swing.JTextField tTexteCharge;
    // End of variables declaration//GEN-END:variables
}
