package be.msyben.vinylManager.gui;

import be.msyben.vinylManager.entities.Album;
import be.msyben.vinylManager.entities.Titre;
import be.msyben.vinylManager.exceptions.VinylManagerException;
import be.msyben.vinylManager.gui.icon.Icons;
import be.msyben.vinylManager.interfaces.WaitListener;
import be.msyben.vinylManager.properties.Language;
import be.msyben.vinylManager.tools.WaitThread;
import be.msyben.vinylManager.tools.log.VinylManagerLogger;
import be.msyben.vinylManager.tools.musicBrainz.MusicBrainzInterface;
import be.msyben.vinylManager.tools.musicBrainz.entities.Release;
import be.msyben.vinylManager.tools.swing.MyJList;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;

/**
 * Gui permettant d'afficher la liste des albums correspondant afin d'en
 * introduire les pistes dans l'interface.
 *
 * @author Mathieu Syben
 */
public final class SearchTracksWindow extends JFrame {

    /**
     * uid
     */
    private static final long serialVersionUID = 15l;
    /**
     * La fenêtre du disque.
     */
    private DisqueWindow disqueWindow;
    /**
     * Le thread d'attente
     */
    private WaitThread waitThread = new WaitThread();
    /**
     * Les releases
     */
    private List<Release> releases;
    /**
     * La liste des résultats.
     */
    private JList<Release> results;
    /**
     * Le ts du dernier clic sur un résultat.
     */
    private long lastClick = 0L;
    /**
     * La dernière sélection
     */
    private int lastSelection = -1;
    /**
     * L'album
     */
    private Album album;

    /**
     * Constructeur privé.
     */
    private SearchTracksWindow() {
    }

    public SearchTracksWindow(DisqueWindow disqueWindowP, Album album) {
        super(Language.getInstance().get("search.track.window.title"));
        this.disqueWindow = disqueWindowP;
        this.album = album;

        setIconImage(Icons.getInstance().icon.getImage());

        this.setSize(500, 300); // 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

        waitThread.addWaitListener(new WaitListener() {
            @Override
            public void onCancel() {
                waitThread.arrete();
                close();
            }
        });
    }

    /**
     * Affiche
     */
    public void display() {
        if (disqueWindow != null) {
            disqueWindow.setEnabled(false);
        }
        waitThread.start();
        new Thread() {
            @Override
            public void run() {
                try {
                    while (!waitThread.isRunning()){
                        try {
                            Thread.sleep(100L);
                        } catch (InterruptedException ex) {
                        }
                    }
                    if (waitThread.isRunning()) {
                        releases = MusicBrainzInterface.getPossibleReleases(album);
                    }
                    if (waitThread.isRunning()) {
                        putElements();
                    }
                    if (waitThread.isRunning()) {
                        results.setListData(releases.toArray(new Release[0]));
                    }

                    if (waitThread.isRunning()) {
                        setVisible(true);
                        waitThread.arrete();
                    }
                } catch (VinylManagerException ex) {
                    VinylManagerLogger.log(ex);
                    if (waitThread.isRunning()) {
                        waitThread.arrete();
                        new ErrorWindow(disqueWindow, Language.getInstance().get("search.track.get.releases.error"), ex);
                        dispose();
                    }
                }
            }
        }.start();
    }

    /**
     * Construit la fenêtre et place les éléments.
     */
    private void putElements() {
        Container c = this.getContentPane();
        c.setLayout(null);
        c.setSize(500, 300);

        JButton fermer = new JButton(Language.getInstance().get("button.fermer"));
        JButton valider = new JButton(Language.getInstance().get("button.valider"));

        results = new MyJList<>();
        results.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        results.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                long now = System.currentTimeMillis();
                int selection = results.getSelectedIndex();
                if (selection == lastSelection && (now - lastClick < 500L)) {
                    selection();
                }
                lastClick = now;
                lastSelection = selection;
            }
        });

        valider.setBounds(100, 245, 100, 25);
        fermer.setBounds(300, 245, 100, 25);

        valider.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                selection();
            }
        });

        fermer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                close();
            }
        });

        JScrollPane scrollPane = new JScrollPane(results);
        scrollPane.setBounds(5, 10, 490, 220);

        c.add(scrollPane);
        c.add(valider);
        c.add(fermer);
        this.toFront();


    }

    public void selection() {
        if (results.isSelectionEmpty()) {
            new ErrorWindow(this, Language.getInstance().get("search.track.no.album.selected.error"));
            return;
        }
        Release release = (Release) results.getSelectedValue();
        
        List<List<Titre>> allFounds;
        try {
            allFounds = MusicBrainzInterface.getTracks(release, album.getCompliation());
        } catch (VinylManagerException ex) {
            VinylManagerLogger.log(ex);
            new ErrorWindow(this, Language.getInstance().get("search.track.get.tracks.error"), ex);
            return;
        }
        close();
        if (disqueWindow != null) {
            disqueWindow.setRelease(allFounds);
        }
    }

    /**
     * Ferme la fenêtre et rend la main à l'appelant.
     */
    private void close() {
        dispose();
        if (disqueWindow != null) {
            disqueWindow.setEnabled(true);
            disqueWindow.toFront();
        }
    }
}
