/*
Copyright 2005-2013 Samuel Gesche

This file is part of ArcEnCiel.

ArcEnCiel 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.

ArcEnCiel 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 ArcEnCiel.  If not, see <http://www.gnu.org/licenses/>.
*/

package ihm;

import data.Chargeur;
import data.Confrontation;
import data.Graphe;
import data.ImportException;

import ihm.townto.EventHandler;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTabbedPane;

import javax.swing.filechooser.FileFilter;

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.util.Vector;

/**
 * Ceci est l'IHM du confronteur. Du moins sa composante de plus haut niveau.
 *
 * @author Samuel GESCHE
 * @version 4.0.1
 * @since 3.0.0
 */
public class FenetrePrincipale extends JFrame {
    private int w = Toolkit.getDefaultToolkit().getScreenSize().width;
    private int h = Toolkit.getDefaultToolkit().getScreenSize().height;

    // Composants principaux
    private JProgressBar enCours;
    private JDialog dEnCours;
    private JLabel lFond;
    private JPanel pConfs;
    private JComponent cConf;
    private JButton bAdd;
    private JButton bSuppr;
    private JButton bPhoto;
    private JButton bSave;

    private Confrontation confrontation;

    // Evaluateur de Ressources
    /*private ActionListener aRess = new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            evalueRess();
        }
    };
    private Timer tRess = new Timer(1000, aRess);
    private JLabel lRess;
    private boolean averti = false;*/

    // Métadonnées
    private String nom = "";
    private String dossier = "";
    private final static String AUTRE = Charte.getMessage("MainFrame_Autre");
    private boolean saved = false;

    // Captures d'Ecran
    private int photoX0 = 0;
    private int photoY0 = 0;
    private int photoX1 = 0;
    private int photoY1 = 0;
    private int stade = 0;
    private MouseAdapter mouse = new MouseAdapter() {
        public void mousePressed(MouseEvent me) {
            if (stade == 0) {
                photoX0 = me.getX();
                photoY0 = me.getY();
                stade = 1;
            } else {
                photoX1 = me.getX();
                photoY1 = me.getY();
                photoFinie();
            }
        }
    };
    private MouseMotionAdapter mouseM = new MouseMotionAdapter() {
        public void mouseMoved(MouseEvent me) {
            if (stade == 1) {
                photoX1 = me.getX();
                photoY1 = me.getY();
                glassPane.repaint();
            }
        }
    };
    private BufferedImage image;
    private JPanel glassPane = new JPanel() {
        public void paint(Graphics g) {
            super.paint(g);
            if (stade == 1) {
                g.setColor(Charte.getForeground());
                g.drawRect(Math.min(photoX0, photoX1) - 1,
                           Math.min(photoY0, photoY1) - 1,
                           Math.abs(photoX1 - photoX0) + 1,
                           Math.abs(photoY1 - photoY0) + 1);
            }
        }
    };

    /**
     * Crée la fenêtre principale de l'application.
     * @param f FenetreInit La fenêtre d'initialisation qui doit être fermée,
     * s'il y a lieu.
     * @since 3.0.0
     */
    public FenetrePrincipale(FenetreInit f) {
        w = this.getToolkit().getScreenSize().width; // dual screen ?
        setSize(w, h-1); // h-1 pour que la barre Windows reste atteignable
        setTitle("ArcEnCiel v"+Charte.getVersion()+" ");
        setUndecorated(true);
        getContentPane().setLayout(null);
        lFond = new JLabel(Charte.getImage());
        lFond.setBackground(Color.WHITE);
        lFond.setSize(w, h-1);

        glassPane.setOpaque(false);
        this.setGlassPane(glassPane);
        glassPane.addMouseListener(mouse);
        glassPane.addMouseMotionListener(mouseM);

        enCours = new JProgressBar(JProgressBar.HORIZONTAL);
        enCours.setIndeterminate(true);
        enCours.setString(Charte.getMessage("MainFrame_MsgEnCours"));
        enCours.setStringPainted(true);
        dEnCours = new JDialog(this, true);
        dEnCours.setUndecorated(true);
        dEnCours.getContentPane().setLayout(new GridLayout(1, 1));
        dEnCours.getContentPane().add(enCours);
        dEnCours.pack();
        dEnCours.setLocation(
            getSize().width / 2 - dEnCours.getSize().width / 2,
            getSize().height / 2 - dEnCours.getSize().height / 2);

        JButton bRed = new JButton(Charte.getMessage("MainFrame_Reduire"));
        bRed.setOpaque(false);
        bRed.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                setExtendedState(JFrame.ICONIFIED);
            }
        });
        bRed.setToolTipText(Charte.getMessage("MainFrame_ReduireTT"));
        bRed.setBounds(w - 202, 0, 100, 20);
        getContentPane().add(bRed);

        final JButton bQuit = new JButton(Charte.getMessage("MainFrame_Quit"));
        bQuit.setOpaque(false);
        bQuit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                quitter();
            }
        });
        bQuit.setToolTipText(Charte.getMessage("MainFrame_QuitTT"));
        bQuit.setBounds(w - 101, 0, 100, 20);
        getContentPane().add(bQuit);

        JLabel logo = new JLabel(Charte.getLogo());
        logo.setBounds(0, 0, 20, 20);
        getContentPane().add(logo);

        bAdd = new JButton(Charte.getMessage("MainFrame_Open"));
        bAdd.setOpaque(false);
        bAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                presenteSauvegardes();
            }
        });
        bAdd.setToolTipText(Charte.getMessage("MainFrame_OpenTT"));
        bAdd.setBounds(21, 0, 100, 20);
        getContentPane().add(bAdd);

        bSuppr = new JButton(Charte.getMessage("MainFrame_Close"));
        bSuppr.setOpaque(false);
        bSuppr.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                suppConf();
            }
        });
        bSuppr.setToolTipText(Charte.getMessage("MainFrame_CloseTT"));
        bSuppr.setBounds(122, 0, 100, 20);
        getContentPane().add(bSuppr);

        bSave = new JButton(Charte.getMessage("MainFrame_Save"));
        bSave.setOpaque(false);
        bSave.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                save();
            }
        });
        bSave.setToolTipText(Charte.getMessage("MainFrame_SaveTT"));
        bSave.setBounds(223, 0, 100, 20);
        getContentPane().add(bSave);

        bPhoto = new JButton(Charte.getMessage("MainFrame_Capture"));
        bPhoto.setOpaque(false);
        bPhoto.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                photo();
            }
        });
        bPhoto.setToolTipText(Charte.getMessage("MainFrame_CaptureTT"));
        bPhoto.setBounds(324, 0, 100, 20);
        getContentPane().add(bPhoto);

        /*lRess = new JLabel("", JLabel.CENTER);
        Charte.formate(lRess);
        lRess.setBounds(202, 0, w - 404, 20);
        getContentPane().add(lRess);*/

        pConfs = new JPanel(new BorderLayout());
        Charte.formate(pConfs);
        pConfs.setOpaque(false);
        pConfs.setBounds(0, 20, w, h - 21);
        getContentPane().add(pConfs);

        getContentPane().add(lFond);
        /*tRess.start();*/
        boutonsFermes();
        setVisible(true);
        f.dispose();
        disBonjour();
    }

    /**
     * Renvoie l'indicateur d'attente (d'autres composants peuvent vouloir
     * indiquer une attente en cours, c'en est le moyen).
     * @return JDialog l'indicateur d'attente
     * @since 3.0.2
     */
    public JDialog getIndicateurAttente() {
        return dEnCours;
    }

    private void boutonsOuverts() {
        bPhoto.setEnabled(true);
        bSave.setEnabled(true);
        bSuppr.setEnabled(true);
        bAdd.setEnabled(false);
    }

    private void boutonsFermes() {
        bPhoto.setEnabled(false);
        bSave.setEnabled(false);
        bSuppr.setEnabled(false);
        bAdd.setEnabled(true);
    }

    private void ajouter() {
        final JFileChooser choix = new JFileChooser("./dat/pdv");
        FileFilter filtre1 = new FileFilter() {
            public boolean accept(File f) {
                return (f.getName().endsWith("leu") || f.isDirectory());
            }

            public String getDescription() {
                return Charte.getMessage("Format_LEU");
            }
        };
        FileFilter filtre2 = new FileFilter() {
            public boolean accept(File f) {
                return (f.getName().endsWith("bch") || f.isDirectory());
            }

            public String getDescription() {
                return Charte.getMessage("Format_BCH");
            }
        };
        FileFilter filtre3 = new FileFilter() {
            public boolean accept(File f) {
                return (f.getName().endsWith("two") || f.isDirectory());
            }

            public String getDescription() {
                return Charte.getMessage("Format_TWO");
            }
        };
        FileFilter filtre4 = new FileFilter() {
            public boolean accept(File f) {
                return (f.getName().endsWith("xtm") || f.isDirectory());
            }

            public String getDescription() {
                return Charte.getMessage("Format_XTM");
            }
        };
        FileFilter filtre6 = new FileFilter() {
            public boolean accept(File f) {
                return (f.getName().endsWith("jou") || f.isDirectory());
            }

            public String getDescription() {
                return Charte.getMessage("Format_JOU");
            }
        };
        FileFilter filtre7 = new FileFilter() {
            public boolean accept(File f) {
                return (f.getName().endsWith("mdn") || f.isDirectory());
            }

            public String getDescription() {
                return Charte.getMessage("Format_MDN");
            }
        };
        FileFilter filtre5 = new FileFilter() {
            public boolean accept(File f) {
                return (f.getName().endsWith("leu") ||
                        f.getName().endsWith("bch") ||
                        f.getName().endsWith("two") ||
                        f.getName().endsWith("xtm") ||
                        f.getName().endsWith("jou") ||
                        f.getName().endsWith("mdn") || f.isDirectory());
            }

            public String getDescription() {
                return Charte.getMessage("Format_all");
            }
        };

        choix.addChoosableFileFilter(filtre1);
        choix.addChoosableFileFilter(filtre2);
        choix.addChoosableFileFilter(filtre3);
        choix.addChoosableFileFilter(filtre4);
        choix.addChoosableFileFilter(filtre6);
        choix.addChoosableFileFilter(filtre7);
        choix.addChoosableFileFilter(filtre5);
        choix.setAcceptAllFileFilterUsed(false);
        choix.setFileSelectionMode(JFileChooser.FILES_ONLY);
        choix.setMultiSelectionEnabled(true);
        int choisi = choix.showOpenDialog(this);
        if (choisi == JFileChooser.APPROVE_OPTION) {
            boutonsOuverts();
            new Thread() {
                public void run() {
                    processusAjout(choix.getSelectedFiles());
                }
            }.start();
            dEnCours.setVisible(true);
        }
        actualise();
    }

    private void suppConf() {
        int choix = JOptionPane.showConfirmDialog(
                this,
                Charte.getMessage("MainFrame_WarnClose"),
                Charte.getMessage("MainFrame_WarnCloseT"),
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                Charte.getSmiley(Charte.CLIN_D_OEIL));
        System.runFinalization();
        System.gc();
        if (choix == JOptionPane.YES_OPTION) {
            boutonsFermes();
            pConfs.remove(cConf);
            cConf = null;
            actualise();
            lFond.setIcon(Charte.getImage());
        }
        dossier = "";
    }

    private void quitter() {
        int choix = 2;
        if (cConf != null) {
            String[] options = {Charte.OUI,
                               Charte.getMessage("MainFrame_QuitWoSave"),
                               Charte.getMessage("MainFrame_NoQuit")};
            choix = JOptionPane.showOptionDialog(
                    JOptionPane.getRootFrame(),
                    Charte.getMessage("MainFrame_WarnQuit"),
                    Charte.getMessage("MainFrame_WarnQuitT"),
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.CLIN_D_OEIL), options, options[0]);
        } else {
            quitter2();
        }
        if (choix == 0) {
            save();
            if (saved) {
                quitter2();
            } else {
                JOptionPane.showMessageDialog(
                        this,
                        Charte.getMessage("MainFrame_RepNoQuit"),
                        Charte.getMessage("MainFrame_RepNoQuitT"),
                        JOptionPane.ERROR_MESSAGE,
                        Charte.getSmiley(Charte.CLIN_D_OEIL));
            }
        } else if (choix == 1) {
            quitter2();
        }
    }

    private void quitter2() {
        Charte.setDernierUtilisateur(nom);
        Charte.saveIni();
        System.out.println("Arrêt de Hippodamos...");
        System.out.println("Arrêt terminé.");
        System.exit(0);
    }

    private void processusAjout(File[] files) {
        Vector graphes = new Vector();
        if (files.length > 1) {
            try {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().endsWith(".leu")) {
                        Graphe nouveauGraphe = Chargeur.chargeLEU(files[i]);
                        graphes.add(nouveauGraphe);
                    } else if (files[i].getName().endsWith(".xml")) {
                        Graphe nouveauGraphe = Chargeur.chargeLEUEN(files[i]);
                        graphes.add(nouveauGraphe);
                    } else if (files[i].getName().endsWith(".bch")) {
                        Graphe nouveauGraphe = Chargeur.chargeBCH(files[i]);
                        graphes.add(nouveauGraphe);
                    } else if (files[i].getName().endsWith(".two")) {
                        Graphe nouveauGraphe = Chargeur.chargeTWO(files[i]);
                        graphes.add(nouveauGraphe);
                    } else if (files[i].getName().endsWith(".xtm")) {
                        Graphe nouveauGraphe = Chargeur.chargeXTM(files[i]);
                        graphes.add(nouveauGraphe);
                    } else if (files[i].getName().endsWith(".jou")) {
                        Graphe nouveauGraphe = Chargeur.chargeJOU(files[i]);
                        graphes.add(nouveauGraphe);
                    } else if (files[i].getName().endsWith(".mdn")) {
                        Graphe nouveauGraphe = Chargeur.chargeMDN(files[i]);
                        graphes.add(nouveauGraphe);
                    }
                }
                Vector aConfronter = new Vector();
                for (int i = 0; i < graphes.size(); i++) {
                    aConfronter.add(graphes.elementAt(i));
                }
                final Graphe[] gAConf = new Graphe[aConfronter.size()];
                aConfronter.toArray(gAConf);

                confrontation = new Confrontation(gAConf);
                cConf = createConfComponent(confrontation);
                pConfs.add(cConf);
                lFond.setIcon(Charte.getFiligrane());
                save();
                if (saved == false) {
                    pConfs.remove(cConf);
                    cConf = null;
                    actualise();
                    boutonsFermes();
                    lFond.setIcon(Charte.getImage());
                }
            } catch (ImportException ie) {
                boutonsFermes();
                lFond.setIcon(Charte.getImage());
                ie.printStackTrace();
            }
        } else {
            JOptionPane.showMessageDialog(
                    this,
                    Charte.getMessage("MainFrame_WarnOneVP"),
                    Charte.getMessage("MainFrame_WarnOneVPT"),
                    JOptionPane.ERROR_MESSAGE,
                    Charte.getSmiley(Charte.DEPRIME));
            boutonsFermes();
            lFond.setIcon(Charte.getImage());
        }
        actualise();
        dEnCours.setVisible(false);
    }

    private void actualise() {
        pConfs.setBackground(new Color(0, 0, 0, 32));
        pConfs.repaint();
        this.getGlassPane().setVisible(true);
        this.getGlassPane().setVisible(false); // fait apparêtre le panneau de confrontation
        repaint();
    }

    private JComponent createConfComponent(final Confrontation confrontation) {
        JPanel pMain = new JPanel(new GridLayout(1, 1));
        pMain.setBorder(Charte.getBorder());
        pMain.setOpaque(false);

        JTabbedPane pTab = new JTabbedPane(JTabbedPane.LEFT,
                                           JTabbedPane.WRAP_TAB_LAYOUT);
        Charte.formate(pTab);

        PanelVisualisation pVisu = new PanelVisualisation(confrontation);
        PanelHomonymes pPolysemies = new PanelHomonymes(confrontation);
        PanelSynonymes pSynonymies = new PanelSynonymes(this, confrontation);
        PanelConfrontation pConfrontation = new PanelConfrontation(this,
                confrontation);
        PanelNotes pNotes = new PanelNotes(confrontation, this);

        pTab.add(Charte.getMessage("MainFrame_TabExplorer"), pVisu);
        pTab.add(Charte.getMessage("MainFrame_TabSeparer"), pPolysemies);
        pTab.add(Charte.getMessage("MainFrame_TabRelier"), pSynonymies);
        pTab.add(Charte.getMessage("MainFrame_TabObserver"), pConfrontation);
        pTab.add(Charte.getMessage("MainFrame_TabPublier"), pNotes);
        for (int i = 0; i < pTab.getTabCount(); i++) {
            pTab.setBackgroundAt(i, new Color(0, 0, 0, 64));
        }
        pTab.setOpaque(false);
        pMain.add(pTab);
        return pMain;
    }

    /*private void evalueRess() {
        lRess.setText(Charte.getMessage("MainFrame_UsedRes") + " " +
                      (int) ((Runtime.getRuntime().totalMemory() -
                              Runtime.getRuntime().freeMemory()) / 1024 / 1024) +
                      "MO");
        if ((1.0 * Runtime.getRuntime().totalMemory() -
             Runtime.getRuntime().freeMemory()) /
            Runtime.getRuntime().maxMemory() > 0.75 && !averti) {
            JOptionPane.showMessageDialog(null,
                                          Charte.getMessage("MainFrame_WarnUsedRes"),
                                          Charte.getMessage("MainFrame_WarnUsedResT"),
                                          JOptionPane.ERROR_MESSAGE,
                                          Charte.getSmiley(Charte.CHOC));
            averti = true;
        }
    }*/

    private void save() {
        saved = false;
        if (cConf != null) {
            File[] f = new File("dat/usr/" + nom).listFiles();
            Vector v = new Vector();
            v.add(AUTRE);
            for (int i = 0; i < f.length; i++) {
                if (f[i].isDirectory()) {
                    v.add(f[i].getName());
                }
            }
            String[] s = new String[v.size()];
            v.toArray(s);
            Object nomD = AUTRE;
            if(s.length>1){
                nomD = JOptionPane.showInputDialog(this,
                        Charte.getMessage("MainFrame_SaveOu"),
                        Charte.getMessage("MainFrame_SaveOuT"),
                        JOptionPane.QUESTION_MESSAGE,
                        Charte.getSmiley(Charte.CONTENT), s, dossier);
            }
            if(nomD != null){
                if (nomD.equals(AUTRE)) {
                    nomD = JOptionPane.showInputDialog(this,
                            Charte.getMessage("MainFrame_NewSave"),
                            Charte.getMessage("MainFrame_NewSaveT"),
                            JOptionPane.INFORMATION_MESSAGE,
                            Charte.getSmiley(Charte.CONTENT), null, dossier);
                }
            }
            if (nomD != null) {
                String nomDossier = nomD.toString();
                if (nomDossier.equals("")) {
                    JOptionPane.showMessageDialog(
                            this,
                            Charte.getMessage("MainFrame_RefusNew"),
                            Charte.getMessage("MainFrame_RefusNewT"),
                            JOptionPane.INFORMATION_MESSAGE,
                            Charte.getSmiley(Charte.CONFUS));
                } else if (nomDossier.equals(AUTRE)) {
                    nomD = JOptionPane.showInputDialog(this,
                            Charte.getMessage("MainFrame_Reserve"),
                            Charte.getMessage("MainFrame_ReserveT"),
                            JOptionPane.INFORMATION_MESSAGE,
                            Charte.getSmiley(Charte.DEPRIME), null, dossier);
                    if (nomD != null) {
                        nomDossier = nomD.toString();
                        if (!(nomDossier.equals("") || nomDossier.equals(AUTRE))) {
                            save2(nomDossier);
                        } else {
                            JOptionPane.showMessageDialog(
                                    this,
                                    Charte.getMessage("MainFrame_Detresse"),
                                    Charte.getMessage("MainFrame_DetresseT"),
                                    JOptionPane.INFORMATION_MESSAGE,
                                    Charte.getSmiley(Charte.PLEUR));
                        }
                    }
                } else {
                    save2(nomDossier);
                }
            }
        } else {
            JOptionPane.showMessageDialog(
                    this,
                    Charte.getMessage("MainFrame_RienASave"),
                    Charte.getMessage("MainFrame_RienASaveT"),
                    JOptionPane.INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.COLERE));
        }
    }

    private void save2(String nomDossier) {
        dossier = nomDossier;
        File d = new File("dat/usr/" + nom + "/" + dossier + "/");
        File f = new File("dat/usr/" + nom + "/" + dossier + "/" +
                          dossier + ".sav");

        try {
            d.mkdirs();
            f.createNewFile();
            confrontation.save(f);
            JOptionPane.showMessageDialog(
                    this,
                    Charte.getMessage("MainFrame_ValideSave"),
                    Charte.getMessage("MainFrame_ValideSaveT"),
                    JOptionPane.
                    INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.CLIN_D_OEIL));
            saved = true;
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(
                    this,
                    Charte.getMessage("MainFrame_WarnNoSave") +
                    ioe.getMessage(),
                    Charte.getMessage("MainFrame_WarnNoSaveT"),
                    JOptionPane.INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.PEUR));
        }
    }

    private void load(final File f) {
        boutonsOuverts();
        new Thread() {
            public void run() {
                load2(f);
            }
        }.start();
        dEnCours.setVisible(true);
    }

    private void load2(File f) {
        try {
            dossier = f.getParentFile().getName();
            confrontation = Confrontation.load(f);
            cConf = createConfComponent(confrontation);
            pConfs.add(cConf);
            lFond.setIcon(Charte.getFiligrane());
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(
                    this,
                    Charte.getMessage("MainFrame_WarnNoLoad") +
                    ioe.getMessage(),
                    Charte.getMessage("MainFrame_WarnNoLoadT"),
                    JOptionPane.INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.PEUR));
            boutonsFermes();
            lFond.setIcon(Charte.getImage());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(
                    this,
                    Charte.getMessage("MainFrame_WarnNoLoad") +
                    e.getClass()+"("+e.getMessage()+")",
                    Charte.getMessage("MainFrame_WarnNoLoadT"),
                    JOptionPane.INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.PEUR));
            boutonsFermes();
            lFond.setIcon(Charte.getImage());
        }
        actualise();
        dEnCours.setVisible(false);
    }

    private void disBonjour() {
        String nomS = Charte.getDernierUtilisateur();
        Object n = JOptionPane.showInputDialog(
            null,
            Charte.getMessage("MainFrame_Welcome"),
            Charte.getMessage("MainFrame_WelcomeT"),
            JOptionPane.QUESTION_MESSAGE,
            Charte.getSmiley(Charte.CONTENT), null, nomS);
        if (n == null) {
            n = JOptionPane.showInputDialog(
                    this,
                    Charte.getMessage("MainFrame_SnifNoName"),
                    Charte.getMessage("MainFrame_SnifNoNameT"),
                    JOptionPane.QUESTION_MESSAGE,
                    Charte.getSmiley(Charte.PLEUR), null, "");
        } else if (n.equals("")) {
            n = JOptionPane.showInputDialog(
                    this,
                    Charte.getMessage("MainFrame_SnifNoName"),
                    Charte.getMessage("MainFrame_SnifNoNameT"),
                    JOptionPane.QUESTION_MESSAGE,
                    Charte.getSmiley(Charte.PLEUR), null, "");
        }
        if (n == null) {
            JOptionPane.showMessageDialog(
                    this,
                    Charte.getMessage("MainFrame_RefuseEnter"),
                    Charte.getMessage("MainFrame_RefuseEnterT"),
                    JOptionPane.INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.TRISTE));
            System.exit(1);
        } else if (n.equals("")) {
            JOptionPane.showMessageDialog(
                    this,
                    Charte.getMessage("MainFrame_RefuseEnter"),
                    Charte.getMessage("MainFrame_RefuseEnterT"),
                    JOptionPane.INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.TRISTE));
            System.exit(1);
        }
        nom = n.toString();
        try {
            File f = new File("dat/usr/" + nom);
            boolean trouve = false;
            if (f.exists() && f.isDirectory()) {
                trouve = true;
            }
            if (!trouve) {
                throw new FileNotFoundException();
            }
            JOptionPane.showMessageDialog(
                    this,
                    Charte.getMessage("MainFrame_Registered") + " " + nom +
                    Charte.getMessage("MainFrame_Registered2"),
                    Charte.getMessage("MainFrame_RegisteredT"),
                    JOptionPane.INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.CONTENT));
            presenteSauvegardes();
        } catch (FileNotFoundException fnfe) {
            JOptionPane.showMessageDialog(
                    this,
                    Charte.getMessage("MainFrame_NewUser") + " " + nom +
                    Charte.getMessage("MainFrame_NewUser2"),
                    Charte.getMessage("MainFrame_NewUserT"),
                    JOptionPane.INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.CONTENT));
            File f = new File("dat/usr/" + nom);
            f.mkdirs();
            ajouter();
        }
    }

    private void presenteSauvegardes() {
        File f = new File("dat/usr/" + nom);
        Vector v = new Vector();
        File[] ff = f.listFiles();
        v.addElement(AUTRE);
        for (int i = 0; i < ff.length; i++) {
            v.addElement(ff[i].getName());
        }
        String[] f2 = new String[v.size()];
        v.toArray(f2);
        if (f2.length > 1) {
            Object choix = JOptionPane.showInputDialog(this,
                    Charte.getMessage("MainFrame_PresentFiles"),
                    Charte.getMessage("MainFrame_PresentFilesT"),
                    JOptionPane.QUESTION_MESSAGE,
                    Charte.getSmiley(Charte.ETUDE), f2, f2[0]);
            if (!(choix == null)) {
                if (!(choix.equals(AUTRE))) {
                    dossier = choix.toString();
                    load(new File("dat/usr/" + nom + "/" + choix + "/" +
                                  choix + ".sav"));
                } else {
                    JOptionPane.showMessageDialog(this,
                                                  Charte.getMessage(
                            "MainFrame_NewFile"),
                                                  Charte.getMessage(
                            "MainFrame_NewFileT"),
                                                  JOptionPane.
                                                  INFORMATION_MESSAGE,
                                                  Charte.getSmiley(Charte.
                            CLIN_D_OEIL));
                    ajouter();
                }
            } else {
                JOptionPane.showMessageDialog(
                        this,
                        Charte.getMessage("MainFrame_NewFile"),
                        Charte.getMessage("MainFrame_NewFileT"),
                        JOptionPane.INFORMATION_MESSAGE,
                        Charte.getSmiley(Charte.CLIN_D_OEIL));
                ajouter();
            }
        } else {
            JOptionPane.showMessageDialog(
                    this,
                    Charte.getMessage("MainFrame_NoFile"),
                    Charte.getMessage("MainFrame_NoFileT"),
                    JOptionPane.INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.CONFUS));
            ajouter();
        }
    }

    /**
     * Renvoie le dossier dans lequel est sauvegardé le contexte de la confrontation.
     * @return File le dossier dans lequel tout est sauvegardé.
     * @since 4.0.3
     */
    File getDossier(){
        return new File("dat/usr/" + nom + "/" + dossier);
    }

    private void photo() {
        stade = 0;
        this.getGlassPane().setVisible(true);
        this.setCursor(Toolkit.getDefaultToolkit().createCustomCursor(
            new ImageIcon("dat/img/photo.gif").getImage(), new Point(15,15),
            "photo"));
        lFond.setIcon(Charte.getImageBlanche());
    }

    private void photoFinie() {
        if (Math.abs(photoX1 - photoX0) > 0 && Math.abs(photoY1 - photoY0) > 0) {
            try {
                Rectangle r = new Rectangle(Math.min(photoX0, photoX1),
                                            Math.min(photoY0, photoY1),
                                            Math.abs(photoX1 - photoX0),
                                            Math.abs(photoY1 - photoY0));
                Robot bot = new Robot();
                image = bot.createScreenCapture(r);
            } catch (AWTException ae) {
                JOptionPane.showMessageDialog(
                        this,
                        Charte.getMessage("MainFrame_WarnNoPhoto") +
                        ae.getMessage(),
                        Charte.getMessage("MainFrame_WarnNoPhotoT"),
                        JOptionPane.INFORMATION_MESSAGE,
                        Charte.getSmiley(Charte.PLEUR));
            }
            String[] options = {Charte.getMessage("MainFrame_PhotoGarder"),
                               Charte.getMessage("MainFrame_PhotoJeter")};
            JLabel l = new JLabel(new ImageIcon(image));
            l.setBorder(Charte.getBorder());
            int choix = JOptionPane.showOptionDialog(this, l,
                    Charte.getMessage("MainFrame_PhotoPrise"),
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.INFORMATION_MESSAGE,
                    Charte.getSmiley(Charte.CONTENT),
                    options, options[0]);
            if (choix == 0) {
                JFileChooser f = new JFileChooser(new File("dat/usr/" + nom +
                        "/" + dossier));
                FileFilter filtre = new FileFilter() {
                    public boolean accept(File f) {
                        return (f.getName().endsWith("png") || f.isDirectory());
                    }

                    public String getDescription() {
                        return Charte.getMessage("Format_PNG");
                    }
                };
                f.addChoosableFileFilter(filtre);
                choix = f.showSaveDialog(this);
                if (choix == JFileChooser.APPROVE_OPTION) {
                    try {
                        File save = f.getSelectedFile();
                        if (!(save.getName().endsWith("png"))) {
                            save = new File(save.getPath() + ".png");
                        }
                        ImageIO.write(image, "png", save);
                        JOptionPane.showMessageDialog(this,
                                Charte.getMessage("MainFrame_ValideSave"),
                                Charte.getMessage("MainFrame_ValideSaveT"),
                                JOptionPane.
                                INFORMATION_MESSAGE,
                                Charte.getSmiley(Charte.
                                                 CLIN_D_OEIL));
                        EventHandler.notifyEvent(EventHandler.NEW_CAPTURE, "");
                    } catch (IOException ioe) {
                        JOptionPane.showMessageDialog(this,
                                Charte.getMessage("MainFrame_WarnNoSave") +
                                ioe.getMessage(),
                                Charte.getMessage("MainFrame_WarnNoSaveT"),
                                JOptionPane.
                                INFORMATION_MESSAGE,
                                Charte.getSmiley(Charte.PEUR));
                    }
                }
            }
        }
        this.getGlassPane().setVisible(false);
        setCursor(Cursor.getDefaultCursor());
        lFond.setIcon(Charte.getFiligrane());
    }
}
