package be.msyben.vinylManager.gui.list.albumList;

import be.msyben.vinylManager.entities.Album;
import be.msyben.vinylManager.tools.swing.MyJList;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * Implémentation de la liste d'albums.
 * <p/>
 * @author Mathieu Syben
 */
public class AlbumList extends AbstractAlbumList {

    /** uid */
    private static final long serialVersionUID = 252865478L;
    /** Les albums */
    private List<Album> allAlbums;
    /** La liste */
    private final JList<Album> list = new MyJList<>();
    /** Le scrollpanel */
    private JScrollPane albumsPane;

    /**
     * Constructeur.
     */
    public AlbumList() {
        list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        list.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                selection();
            }
        });

        list.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {

                if (e.getClickCount() == 2) {
                    int index = list.locationToIndex(e.getPoint());
                    if (index <= list.getModel().getSize()) {
                        doubleClic();
                    }
                }

            }
        });
        albumsPane = new JScrollPane(list);
    }

    @Override
    public void updateList(List<Album> albums) {
        allAlbums = albums;

        list.setListData(allAlbums.toArray(new Album[0]));
        if (!albums.isEmpty()) {
            list.setSelectedIndex(0);
        }
    }

    @Override
    public Album getCurrentAlbum() {
        if (list.isSelectionEmpty()) {
            return null;
        } else {
            return (Album) list.getSelectedValue();
        }
    }

    @Override
    public void select(Album album) {
        if (album == null) {
            list.clearSelection();
            return;
        }
        if (allAlbums == null) {
            list.clearSelection();
            return;
        }
        int idx = allAlbums.indexOf(album);
        if (idx >= 0) {
            list.setSelectedIndex(idx);
        } else {
            list.clearSelection();
        }
    }

    @Override
    public Component getComponent() {
        return albumsPane;
    }

    @Override
    public void setEnabled(boolean enabled) {
        albumsPane.setEnabled(enabled);
        list.setEnabled(enabled);
    }

    @Override
    public void setFont(Font font) {
        list.setFont(font);
    }
}
