package be.msyben.vinylManager.gui;

import be.msyben.vinylManager.controller.Controller;
import be.msyben.vinylManager.data.Data;
import be.msyben.vinylManager.entities.Album;
import be.msyben.vinylManager.entities.Disque;
import be.msyben.vinylManager.entities.Image;
import be.msyben.vinylManager.entities.Titre;
import be.msyben.vinylManager.exceptions.VinylManagerException;
import be.msyben.vinylManager.gui.icon.Icons;
import be.msyben.vinylManager.properties.*;
import be.msyben.vinylManager.tools.FontTool;
import be.msyben.vinylManager.tools.filter.FileFilterImages;
import be.msyben.vinylManager.tools.swing.MyJComboBox;
import be.msyben.vinylManager.tools.Tools;
import be.msyben.vinylManager.tools.log.VinylManagerLogger;
import be.msyben.vinylManager.tools.swing.SuggestionComboBox2;
import com.toedter.calendar.JDateChooser;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

/**
 * JFrame d'affichage d'un album
 *
 * @author Mathieu Syben
 */
public class AlbumWindow extends JFrame implements ActionListener {

    /**
     * uid
     */
    private static final long serialVersionUID = 4l;
    private JCheckBox compilation = new JCheckBox(Language.getInstance().get("name.compilation"));
    private JCheckBox possede = new JCheckBox(Language.getInstance().get("name.possede"), true);
    private JTextField annee = new JTextField();
    private JTextField anneeParution = new JTextField();
    private SuggestionComboBox2 artiste;
    private JTextField artisteSort = new JTextField();
    private SuggestionComboBox2 editeur;
    private JTextArea commentaireArea = new JTextArea();
    private JScrollPane commentaire = new JScrollPane(commentaireArea);
    private SuggestionComboBox2 pays;
    private SuggestionComboBox2 genre;
    /**
     * Le JComboBox contenant l'état
     */
    private MyJComboBox<Cotation> etat = new MyJComboBox<>();
    /**
     * L'image
     */
    private JLabel image = new JLabel();
    /**
     * Le textfield contenant les musiciens
     */
    private JTextArea musiciensArea = new JTextArea();
    private JScrollPane musiciens = new JScrollPane(musiciensArea);
    /**
     * Le textfield contenant la référence
     */
    private JTextField reference = new JTextField();
    /**
     * Le textfield contenant le titre
     */
    private JTextField titre = new JTextField();
    /**
     * Le textfield contenant la valeur
     */
    private JTextField valeur = new JTextField();
    private SuggestionComboBox2 compositeur;
    private SuggestionComboBox2 chef;
    private SuggestionComboBox2 orchestre;
    private SuggestionComboBox2 parolier;
    private SuggestionComboBox2 location;
    private JComboBox<Support> support = new MyJComboBox<>();
    private JDateChooser dateAchat = new JDateChooser(null, Preferences.getInstance().get(Preferences.DATE_FORMAT, "dd/MM/yyyy"));
    /**
     * l'album en cours d'édition
     */
    private Album editAlbum = null;
    /**
     * le bouton ok
     */
    private JButton ok = new JButton(Language.getInstance().get("button.valider"));
    /**
     * le bouton cancel
     */
    private JButton cancel = new JButton(Language.getInstance().get("button.annuler"));
    /**
     * le bouton get image
     */
    private JButton getImageFile = new JButton(Language.getInstance().get("button.select.image"), Icons.getInstance().folder);
    /**
     * le bouton get image
     */
    private JButton getImageLastFm = new JButton(Language.getInstance().get("button.select.image.lastfm"), Icons.getInstance().loupe);
    /**
     * le bouton supprime image
     */
    private JButton supprimeImage = new JButton(Language.getInstance().get("button.supprimer.image"));
    private JButton definirDefaut = new JButton(Language.getInstance().get("button.definir.defaut"));
    /**
     * L'image
     */
    private Image imageF;
    private List<Image> otherImages = new ArrayList<>();
    private JButton imgPrev = new JButton(Icons.getInstance().leftArrow);
    private JButton imgNext = new JButton(Icons.getInstance().rightArrow);
    /*
     * -1 pour l'image imageF.
     * entre 0 et otherImages.size pour les autres.
     */
    private int currentImg = -1;
    /**
     * Le controller
     */
    private Controller controller;

    /**
     * Creates a new instance of AlbumWindow.
     */
    public AlbumWindow(Controller controller) {
        super(Language.getInstance().get("album.window.new.title"));
        this.controller = controller;
        setIconImage(Icons.getInstance().icon.getImage());
        MainWindow.getInstance().setEnabled(false);
        this.setSize(650, 590); //On donne une taille à notre fenêtre
        this.setLocationRelativeTo(null); //On centre la fenêtre sur l'ecran
        this.setResizable(false); //On interdit la redimensionnement de la fenêtre
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); //On dit à l'application de se fermer

        putElements();

        setVisible(true);
    }

    /**
     * Constructeur.
     *
     * @param editAlbum l'album à éditer
     */
    public AlbumWindow(Controller controller, Album editAlbum) {
        super(Language.getInstance().get("album.window.edit.title"));
        this.controller = controller;
        this.editAlbum = editAlbum;
        setIconImage(Icons.getInstance().icon.getImage());
        MainWindow.getInstance().setEnabled(false);

        this.setSize(650, 590); //On donne une taille à notre fenêtre
        this.setLocationRelativeTo(null); //On centre la fenêtre sur l'ecran
        this.setResizable(false); //On interdit la redimensionnement de la fenêtre
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); //On dit à l'application de se fermer


        putElements();

        annee.setText(editAlbum.getAnnee());
        anneeParution.setText(editAlbum.getAnneeParution());
        artiste.setText(editAlbum.getArtiste());
        artisteSort.setText(editAlbum.getArtisteSort());
        titre.setText(editAlbum.getTitre());
        support.setSelectedItem(Support.getSupport(editAlbum.getSupport()));
        commentaireArea.setText(editAlbum.getCommentaire());
        genre.setText(editAlbum.getGenre());
        valeur.setText(editAlbum.getValeur());
        compilation.setSelected(editAlbum.getCompliation());
        possede.setSelected(editAlbum.getPossede());
        dateAchat.setDate(editAlbum.getDateAchat());
        if (compilation.isSelected()) {
            artiste.setEnabled(false);
        }
        


        boolean etatset = false;
        for (Cotation c : Cotation.cotations) {
            if (c.equals(editAlbum.getEtat())) {
                etat.setSelectedItem(c);
                etatset = true;
                break;
            }
        }
        if (!etatset) {
            etat.setSelectedItem(Cotation.vide);
        }
        editeur.setText(editAlbum.getEditeur());
        musiciensArea.setText(editAlbum.getMusiciens());
        reference.setText(editAlbum.getReference());
        compositeur.setText(editAlbum.getCompositeur());
        chef.setText(editAlbum.getChef());
        orchestre.setText(editAlbum.getOrchestre());
        parolier.setText(editAlbum.getParolier());
        location.setText(editAlbum.getLocation());
        imageF = editAlbum.getImage();
       // otherImages = editAlbum.getOtherImages();
        otherImages = new ArrayList<>();
        for (Image i : editAlbum.getOtherImages()) {
            otherImages.add(i);
        }

        pays.setText(editAlbum.getPays());
        try {
            displayImage();
        } catch (VinylManagerException ex) {
        }

        setDisplayButtonImg();


        setVisible(true);
    }

    /**
     * Place les éléments dans la fenêtre
     */
    private void putElements() {

        JLabel anneeL = new JLabel(Language.getInstance().get("name.annee"));
        JLabel artisteL = new JLabel(Language.getInstance().get("name.artiste"));
        JLabel artisteSortL = new JLabel(Language.getInstance().get("name.artiste.sort"));
        JLabel editeurL = new JLabel(Language.getInstance().get("name.editeur"));
        JLabel commentaireL = new JLabel(Language.getInstance().get("name.commentaire"));
        JLabel genreL = new JLabel(Language.getInstance().get("name.genre"));
        JLabel imageL = new JLabel(Language.getInstance().get("name.image"));
        JLabel etatL = new JLabel(Language.getInstance().get("name.etat"));
        JLabel musiciensL = new JLabel(Language.getInstance().get("name.musiciens"));
        JLabel referenceL = new JLabel(Language.getInstance().get("name.reference"));
        JLabel titreL = new JLabel(Language.getInstance().get("name.titre"));
        JLabel valeurL = new JLabel(Language.getInstance().get("name.valeur"));
        JLabel chefL = new JLabel(Language.getInstance().get("name.chef"));
        JLabel orchestreL = new JLabel(Language.getInstance().get("name.orchestre"));
        JLabel compositeurL = new JLabel(Language.getInstance().get("name.compositeur.short"));
        JLabel supportL = new JLabel(Language.getInstance().get("name.support"));
        JLabel dateAchatL = new JLabel(Language.getInstance().get("name.date.achat"));
        JLabel parolierL = new JLabel(Language.getInstance().get("name.parolier"));
        JLabel locationL = new JLabel(Language.getInstance().get("name.location"));
        JLabel paysL = new JLabel(Language.getInstance().get("name.pays"));




        Container c = this.getContentPane();
        c.setLayout(null);
        c.setSize(700, 590);

        compilation.setBounds(5, 5, 150, 25);
        c.add(compilation);
        
        possede.setBounds(170, 5,100,25);
        c.add(possede);

        compilation.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (compilation.isSelected()) {
                    artiste.setText("");
                    artiste.setEnabled(false);
                } else {
                    artiste.setEnabled(true);
                }
            }
        });

        Set<String> allArtists = new HashSet<>();
        Set<String> allEditeurs = new HashSet<>();
        Set<String> allCompositeurs = new HashSet<>();
        Set<String> allChefs = new HashSet<>();
        Set<String> allOrchestres = new HashSet<>();
        Set<String> allParoliers = new HashSet<>();
        Set<String> allLocations = new HashSet<>();
        Set<String> allPays = new HashSet<>(Pays.paysList);
        Set<String> allGenre = new HashSet<>(Genres.genresList);
        for (Album alb : Data.getInstance().getCollection().getAlbums()) {
            allArtists.add(alb.getArtisteForList());
            if (alb.getEditeur() != null && !alb.getEditeur().isEmpty()) {
                allEditeurs.add(alb.getEditeur());
            }
            if (alb.getCompositeur() != null && !alb.getCompositeur().isEmpty()) {
                allCompositeurs.add(alb.getCompositeur());
            }
            if (alb.getChef() != null && !alb.getChef().isEmpty()) {
                allChefs.add(alb.getChef());
            }
            if (alb.getOrchestre() != null && !alb.getOrchestre().isEmpty()) {
                allOrchestres.add(alb.getOrchestre());
            }
            if (alb.getParolier() != null && !alb.getParolier().isEmpty()) {
                allParoliers.add(alb.getParolier());
            }
            if (alb.getLocation()!= null && !alb.getLocation().isEmpty()) {
                allLocations.add(alb.getLocation());
            }
            if (alb.getPays() != null && !alb.getPays().isEmpty()) {
                allPays.add(alb.getPays());
            }
            if (alb.getGenre() != null && !alb.getGenre().isEmpty()) {
                allGenre.add(alb.getGenre());
            }
        }
        artiste = new SuggestionComboBox2(new ArrayList<>(allArtists));
        editeur = new SuggestionComboBox2(new ArrayList<>(allEditeurs));
        compositeur = new SuggestionComboBox2(new ArrayList<>(allCompositeurs));
        chef = new SuggestionComboBox2(new ArrayList<>(allChefs));
        orchestre = new SuggestionComboBox2(new ArrayList<>(allOrchestres));
        parolier = new SuggestionComboBox2(new ArrayList<>(allParoliers));
        location = new SuggestionComboBox2(new ArrayList<>(allLocations));
        pays = new SuggestionComboBox2(new ArrayList<>(allPays));
        genre = new SuggestionComboBox2(new ArrayList<>(allGenre));

        artisteL.setBounds(5, 35, 55, 15);
        c.add(artisteL);
        artiste.setBounds(60, 30, 265, 25);
        artiste.setSize(265, 25, 150);
        c.add(artiste);
        
        artisteSortL.setBounds(5, 65, 55, 15);
        c.add(artisteSortL);
        artisteSort.setBounds(60, 60, 265, 25);
        c.add(artisteSort);

        titreL.setBounds(5, 95, 55, 15);
        c.add(titreL);
        titre.setBounds(60, 90, 265, 25);
        c.add(titre);

        compositeurL.setBounds(5, 125, 55, 15);
        compositeurL.setToolTipText(Language.getInstance().get("name.compositeur.full"));
        compositeur.setBounds(60, 120, 265, 25);
        compositeur.setSize(265, 25, 150);
        c.add(compositeurL);
        c.add(compositeur);

        supportL.setBounds(5, 155, 55, 15);
        c.add(supportL);
        for (Support sup : Support.values()) {
            support.addItem(sup);
        }
        support.setBounds(60, 150, 95, 25);
        c.add(support);

        etatL.setBounds(170, 155, 55, 15);
        c.add(etatL);
        for (Cotation cot : Cotation.cotations) {
            etat.addItem(cot);
        }
        etat.setBounds(230, 150, 95, 25);
        c.add(etat);

        editeurL.setBounds(5, 185, 55, 15);
        c.add(editeurL);
        editeur.setBounds(60, 180, 95, 25);
        editeur.setSize(95, 25, 150, 200);
        c.add(editeur);

        genreL.setBounds(170, 185, 60, 15);
        c.add(genreL);
        genre.setBounds(230, 180, 95, 25);
        genre.setSize(95, 25, 150, 200);
        c.add(genre);

        anneeL.setBounds(5, 215, 55, 15);
        c.add(anneeL);
        annee.setBounds(60, 210, 45, 25);
        c.add(annee);
        anneeParution.setBounds(110, 210, 45, 25);
        anneeParution.setToolTipText(Language.getInstance().get("name.annee.parution"));
        c.add(anneeParution);

        referenceL.setBounds(170, 215, 60, 15);
        c.add(referenceL);
        reference.setBounds(230, 210, 95, 25);
        c.add(reference);


        chefL.setBounds(5, 245, 55, 15);
        chef.setBounds(60, 240, 95, 25);
        chef.setSize(95, 25, 150, 200);
        c.add(chefL);
        c.add(chef);
        orchestreL.setBounds(170, 245, 60, 15);
        orchestre.setBounds(230, 240, 95, 25);
        orchestre.setSize(95, 25, 150, 200);
        c.add(orchestreL);
        c.add(orchestre);

        valeurL.setBounds(5, 275, 60, 15);
        c.add(valeurL);
        valeur.setBounds(60, 270, 95, 25);
        c.add(valeur);

        dateAchatL.setBounds(170, 275, 60, 15);
        dateAchat.getJCalendar().setTodayButtonVisible(true);
        dateAchat.getJCalendar().setNullDateButtonVisible(true);
        dateAchat.setToolTipText(null);
        dateAchat.setFont(FontTool.font2);
        ((JTextField) dateAchat.getDateEditor().getUiComponent()).setEditable(false);
        dateAchat.getDateEditor().getUiComponent().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    AlbumWindow.this.dateAchat.setDate(new Date());
                }
            }
        });
        dateAchat.setBounds(230, 270, 95, 25);
        c.add(dateAchatL);
        c.add(dateAchat);

        parolierL.setBounds(5, 305, 60, 15);
        c.add(parolierL);
        parolier.setBounds(60, 300, 95, 25);
        parolier.setSize(95, 25, 150, 200);
        c.add(parolier);
        paysL.setBounds(170, 305, 60, 15);
        pays.setBounds(230, 300, 95, 25);
        pays.setSize(95, 25, 150, 200);
        c.add(paysL);
        c.add(pays);
        
        locationL.setBounds(5, 335, 60, 15);
        c.add(locationL);
        location.setBounds(60, 330, 95, 25);
        location.setSize(95, 25, 150, 200);
        c.add(location);

        commentaireL.setBounds(5, 365, 200, 15);
        c.add(commentaireL);
        commentaire.setBounds(5, 380, 320, 120);
        commentaire.setBackground(titre.getBackground());
        commentaire.setBorder(titre.getBorder());
        c.add(commentaire);

        imageL.setBounds(350, 185, 55, 15);
        c.add(imageL);
        getImageFile.addActionListener(this);
        getImageLastFm.setBounds(405, 185, 200, 20);
        c.add(getImageLastFm);
        getImageFile.setBounds(405, 210, 200, 20);
        c.add(getImageFile);
        getImageLastFm.addActionListener(this);
        image.setBounds(405, 235, 200, 200);
        c.add(image);
        image.setBorder(new LineBorder(Color.BLACK, 1));
        image.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    final JPopupMenu popup = new JPopupMenu();
                    JMenuItem paste = new JMenuItem(Language.getInstance().get("name.paste"));
                    JMenuItem copy = new JMenuItem(Language.getInstance().get("name.copy"));
                    paste.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            addImagePaste();
                            popup.setVisible(false);
                        }
                    });
                    copy.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            if (currentImg == -1) {
                                if (imageF != null) {
                                    Tools.setClipboard(new ImageIcon(imageF.getContenu()));
                                } else {
                                    Tools.clearClipboard();
                                }
                            } else {
                                Tools.setClipboard(new ImageIcon(otherImages.get(currentImg).getContenu()));
                            }
                            popup.setVisible(false);
                        }
                    });
                    paste.setEnabled(Tools.isImageInClipboard());
                    copy.setEnabled(imageF != null);
                    popup.add(copy);
                    popup.add(paste);
                    popup.setVisible(true);
                    popup.show(e.getComponent(), e.getX(), e.getY());
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                if (image.getIcon() != null) {
                    setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            }
        });

        imgPrev.setBounds(370, 320, 30, 30);
        c.add(imgPrev);
        imgPrev.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentImg--;
                try {
                    displayImage();
                } catch (VinylManagerException ex) {
                }
                setDisplayButtonImg();
            }
        });
        imgNext.setBounds(610, 320, 30, 30);
        c.add(imgNext);
        imgNext.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentImg++;
                try {
                    displayImage();
                } catch (VinylManagerException ex) {
                }
                setDisplayButtonImg();
            }
        });

        supprimeImage.setBounds(405, 440, 200, 20);
        supprimeImage.addActionListener(this);

        c.add(supprimeImage);


        definirDefaut.setBounds(405, 465, 200, 20);
        definirDefaut.addActionListener(this);

        c.add(definirDefaut);

        musiciensL.setBounds(350, 5, 200, 15);
        c.add(musiciensL);
        musiciens.setBounds(355, 20, 265, 150);
        musiciens.setBackground(titre.getBackground());
        musiciens.setBorder(titre.getBorder());
        c.add(musiciens);



        ok.setBounds(5, 520, 100, 25);
        ok.addActionListener(this);
        c.add(ok);

        cancel.setBounds(150, 520, 100, 25);
        cancel.addActionListener(this);
        c.add(cancel);

        AbstractAction pasteImage = new AbstractAction() {
            private static final long serialVersionUID = 62778346243l;

            @Override
            public void actionPerformed(ActionEvent e) {
                addImagePaste();
            }
        };
        AbstractAction copyImage = new AbstractAction() {
            private static final long serialVersionUID = 266946243l;

            @Override
            public void actionPerformed(ActionEvent e) {
                if (currentImg == -1) {
                    if (imageF != null) {
                        Tools.setClipboard(new ImageIcon(imageF.getContenu()));
                    } else {
                        Tools.clearClipboard();
                    }
                } else {
                    Tools.setClipboard(new ImageIcon(otherImages.get(currentImg).getContenu()));
                }
            }
        };

        setDisplayButtonImg();

        InputMap im = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        getRootPane().getActionMap().put("pasteImage", pasteImage);
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), "pasteImage");
        getRootPane().getActionMap().put("copyImage", copyImage);
        im.put(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK), "copyImage");
    }

    /**
     * Appelé quand un action a été faite
     *
     * @param e l'action
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if (source == ok) {
            
            if (!compilation.isSelected() && (artiste.getText() == null || artiste.getText().trim().equals(""))) {
                new ErrorWindow(this, Language.getInstance().get("error.album.no.artiste"));
                return;
            }
            if (titre.getText() == null || titre.getText().trim().equals("")) {
                new ErrorWindow(this, Language.getInstance().get("error.album.no.titre"));
                return;
            }
            
            Album backup;
            boolean insert = false;
            if (editAlbum == null) {
                editAlbum = new Album();
                insert = true;
                backup = new Album();
            } else {
                try {
                    backup = editAlbum.clone();
                } catch (CloneNotSupportedException ex) {
                    backup = new Album();
                }
            }


            editAlbum.setCompilation(compilation.isSelected());
            //si pas compilation, je vide les noms des artistes des pistes!
            if (!compilation.isSelected()) {
                for (Disque d : editAlbum.getDisques()) {
                    for (Titre t : d.getFaceA()) {
                        t.setArtiste("");
                    }
                    for (Titre t : d.getFaceB()) {
                        t.setArtiste("");
                    }
                }
            }
            editAlbum.setPossede(possede.isSelected());
            editAlbum.setAnnee(annee.getText());
            editAlbum.setAnneeParution(anneeParution.getText());
            editAlbum.setArtiste(artiste.getText());
            editAlbum.setArtisteSort(artisteSort.getText());
            editAlbum.setTitre(titre.getText());
            editAlbum.setCommentaire(commentaireArea.getText());
            editAlbum.setGenre(genre.getText());
            editAlbum.setEtat(((Cotation) etat.getSelectedItem()).getValeur());
            editAlbum.setEditeur(editeur.getText());
            editAlbum.setImage(imageF);
            editAlbum.setOtherImages(otherImages);
            editAlbum.setMusiciens(musiciensArea.getText());
            editAlbum.setReference(reference.getText());
            editAlbum.setValeur(valeur.getText());
            editAlbum.setChef(chef.getText());
            editAlbum.setOrchestre(orchestre.getText());
            editAlbum.setCompositeur(compositeur.getText());
            editAlbum.setSupport(((Support) support.getSelectedItem()).getId());
            editAlbum.setDateAchat(dateAchat.getDate());
            editAlbum.setParolier(parolier.getText());
            editAlbum.setLocation(location.getText());
            editAlbum.setPays(pays.getText());

            if (insert) {
                try {
                    controller.addAlbum(editAlbum);
                } catch (VinylManagerException ex) {
                    VinylManagerLogger.log(ex);
                    new ErrorWindow(this, ex.getMessage(), ex);
                    editAlbum = null;
                    return;
                }
            }
            if (!insert) {
                try {
                    controller.editedAlbum(editAlbum);
                } catch (VinylManagerException ex) {
                    VinylManagerLogger.log("error.image.message", ex);
                    new ErrorWindow(this, ex.getMessage(), ex);
                    editAlbum.copyProperties(backup);
                    return;
                }
            }
            this.dispose();
            MainWindow.getInstance().toFront();
            MainWindow.getInstance().setEnabled(true);
        }
        if (source == cancel) {
            this.dispose();
            MainWindow.getInstance().toFront();
            MainWindow.getInstance().setEnabled(true);
        }

        if (source == supprimeImage) {
            if (currentImg == -1) {
                if (otherImages != null && !otherImages.isEmpty()) {
                    imageF = otherImages.get(0);
                    otherImages.remove(0);
                } else {
                    imageF = null;
                }
            } else {
                otherImages.remove(currentImg);
                if (currentImg > otherImages.size() - 1) {
                    currentImg = -1;
                }
            }

            setDisplayButtonImg();
            try {
                displayImage();
            } catch (VinylManagerException ex) {
            }


            toFront();
        }

        if (source == definirDefaut) {
            if (currentImg >= 0 && currentImg < otherImages.size()) {
                Image def = otherImages.get(currentImg);
                otherImages.set(currentImg, imageF);
                imageF = def;
                currentImg = -1;
                try {
                    setDisplayButtonImg();
                    displayImage();
                } catch (VinylManagerException ex) {
                    ex.printStackTrace();
                }
            }
        }

        if (source == getImageLastFm) {
            String albS = titre.getText();
            String artS = artiste.getText();
            if (albS == null || albS.length() == 0) {
                new ErrorWindow(this, Language.getInstance().get("error.album.no.title"));
                return;
            }
            if (artS == null || artS.length() == 0) {
                artS = "";
            }

            new SearchImageWindow(this, artS, albS).display();

        }

        if (source == getImageFile) {
            try {
                this.setEnabled(false);
                String imageDir = Preferences.getInstance().get(Preferences.LAST_IMAGE_DIR);
                JFileChooser fc = null;
                if (imageDir != null) {
                    File imageDirFile = new File(imageDir);
                    if (imageDirFile.exists() && imageDirFile.isDirectory()) {
                        fc = new JFileChooser(imageDirFile);
                    } else {
                        fc = new JFileChooser(System.getProperty("user.home"));
                    }
                } else {
                    fc = new JFileChooser(System.getProperty("user.home"));
                }
                fc.setDialogTitle(Language.getInstance().get("open.dialog.title"));
                fc.setMultiSelectionEnabled(false);
                fc.setAcceptAllFileFilterUsed(false);
                fc.setFileFilter(new FileFilterImages());
                int res = fc.showOpenDialog(this);
                this.setEnabled(true);
                if (res == JFileChooser.APPROVE_OPTION) {
                    File f = fc.getSelectedFile();
                    if (f.exists()) {

                        boolean resize = Preferences.getInstance().get(Preferences.RESIZE_PICTURES, "Y").equals("Y");

                        byte[] contenu = Tools.getContenu(f);
                        byte[] contenuReduit = Tools.getReducedImage(contenu);


                        if (resize) {
                            contenu = contenuReduit;
                        }

                        if (imageF == null) {
                            imageF = new Image();
                            imageF.setNom(f.getName());
                            imageF.setContenu(contenu);
                            currentImg = -1;
                        } else {
                            Image img = new Image();
                            img.setNom(f.getName());
                            img.setContenu(contenu);
                            otherImages.add(img);
                            currentImg = otherImages.size() - 1;
                        }


                        setDisplayButtonImg();
                        displayImage();

                        Preferences.getInstance().set(Preferences.LAST_IMAGE_DIR, f.getParent());
                        toFront();
                    } else {
                        new ErrorWindow(this, Language.getInstance().get("error.album.image.not.exists"));
                    }
                } else {
                    toFront();
                }

            } catch (VinylManagerException ex) {
                VinylManagerLogger.log("error.album.image.not.exists", ex);
                new ErrorWindow(this, Language.getInstance().get("error.album.image.not.exists"), ex);
            }
        }
    }

    /**
     * Sette l'image.
     *
     * @param img l'image.
     */
    public void setImage(Image img) {
        try {
            boolean resize = Preferences.getInstance().get(Preferences.RESIZE_PICTURES, "Y").equals("Y");

            byte[] contenu = img.getContenu();
            byte[] contenuReduit;

            contenuReduit = Tools.getReducedImage(contenu);


            ImageIcon im = new ImageIcon(contenuReduit);
            image.setIcon(im);

            if (resize) {
                contenu = contenuReduit;
            }

            if (imageF == null) {

                imageF = new Image();
                imageF.setNom(img.getNom());
                imageF.setContenu(contenu);
                currentImg = -1;
            } else {
                Image innerIm = new Image();
                innerIm.setNom(img.getNom());
                innerIm.setContenu(contenu);
                otherImages.add(innerIm);
                currentImg = otherImages.size() - 1;
            }

            setDisplayButtonImg();
            displayImage();

        } catch (VinylManagerException ex) {
            VinylManagerLogger.log("error.album.image.not.exists", ex);
            new ErrorWindow(this, Language.getInstance().get("error.album.image.not.exists"), ex);
        }
    }

    private void addImagePaste() {

        BufferedImage img = Tools.getImageFromClipboard();
        if (img != null) {
            ByteArrayOutputStream baos = null;
            try {
                baos = new ByteArrayOutputStream();
                ImageIO.write(img, "png", baos);
                Image myImage = new Image();
                myImage.setContenu(baos.toByteArray());
                myImage.setNom("pasted.png");
                setImage(myImage);
            } catch (IOException ex) {
                VinylManagerLogger.log(ex);
            } finally {
                Tools.closeQuietly(baos);
            }
        }
    }

    private void setDisplayButtonImg() {
        if (imageF == null) {
            definirDefaut.setEnabled(false);
            imgPrev.setVisible(false);
            imgNext.setVisible(false);
        } else {
            if (otherImages == null || otherImages.isEmpty()) {
                definirDefaut.setEnabled(false);
                imgPrev.setVisible(false);
                imgNext.setVisible(false);
            } else {
                if (currentImg == -1) {
                    definirDefaut.setEnabled(false);
                    imgPrev.setVisible(false);
                    imgNext.setVisible(true);
                } else if (currentImg == otherImages.size() - 1) {
                    definirDefaut.setEnabled(true);
                    imgPrev.setVisible(true);
                    imgNext.setVisible(false);
                } else {
                    definirDefaut.setEnabled(true);
                    imgPrev.setVisible(true);
                    imgNext.setVisible(true);
                }
            }
        }
    }

    private void displayImage() throws VinylManagerException {
        byte[] contenu = null;
        if (currentImg == -1) {
            if (imageF != null) {
                contenu = imageF.getContenu();
            }
        } else {
            contenu = otherImages.get(currentImg).getContenu();
        }
        if (contenu != null) {
            byte[] contenuReduit = Tools.getReducedImage(contenu);

            ImageIcon im = new ImageIcon(contenuReduit);
            image.setIcon(im);
            supprimeImage.setEnabled(true);
        } else {
            image.setIcon(null);
            supprimeImage.setEnabled(false);
        }

    }
}
