/* * Copyright (C) 2022 jimj316 * * This program 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. * * This program 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 this program. If not, see . */ package moe.nekojimi.chords; import com.amihaiemil.eoyaml.Yaml; import com.amihaiemil.eoyaml.YamlMapping; import com.amihaiemil.eoyaml.YamlSequence; import com.amihaiemil.eoyaml.YamlSequenceBuilder; import java.net.MalformedURLException; import java.util.*; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author jimj316 */ public class Playlist implements Consumer { private static final int SHUFFLE_DONT_REPEAT_LAST = 3; private final String name; private final List tracks = new ArrayList<>(); private final LinkedList playHistory = new LinkedList<>(); public Playlist(String name) { this.name = name; } public YamlMapping toYaml() { YamlSequenceBuilder trackList = Yaml.createYamlSequenceBuilder(); for (Track track : tracks) trackList = trackList.add(track.toYaml()); return Yaml.createYamlMappingBuilder() .add("name", name) .add("tracks", trackList.build()) .build(); } public static Playlist fromYaml(YamlMapping yaml) { Playlist ret = new Playlist(yaml.string("name")); YamlSequence trackList = yaml.value("tracks").asSequence(); for (int i = 0; i < trackList.size(); i++) { try { ret.addTrack(Track.fromYaml(trackList.yamlMapping(i))); } catch (MalformedURLException ex) { Logger.getLogger(Playlist.class.getName()).log(Level.SEVERE, null, ex); } } return ret; } public void addTrack(Track track) { track.setKept(true); tracks.add(track); } public String getName() { return name; } public List getTracks() { return tracks; } public Track getNextTrack() { Track ret; // copy the track list List toShuffle = new LinkedList<>(tracks); // remove play history from candidates, latest first, unless we'd have less than 2 options for (int i = playHistory.size() - 1; i >= 0; i--) { if (toShuffle.size() <= 2) break; toShuffle.remove(playHistory.get(i)); } Collections.shuffle(toShuffle); ret = toShuffle.get(0); playHistory.add(ret); if (playHistory.size() > SHUFFLE_DONT_REPEAT_LAST) playHistory.remove(); return ret; } @Override public void accept(Track t) { addTrack(t); } }