package br.net.venson;

import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

class Player implements Runnable {
    private final PlaylistIterator iterator;

    private volatile boolean playing = false;
    private volatile boolean stop = false;
    private volatile boolean next = false;
    private volatile boolean previous = false;
    private Clip currentClip;

    public Player(PlaylistIterator iterator) {
        this.iterator = iterator;
    }

    public void play() {
        if (!playing) {
            playing = true;
            new Thread(this, "PlayerThread").start();
        }
    }

    public void stop() {
        stop = true;
        if (currentClip != null) currentClip.stop();
    }

    public void next() {
        next = true;
        if (currentClip != null) currentClip.stop();
    }

    public void previous() {
        if (iterator.hasPrevious()) {
            previous = true;
            if (currentClip != null) currentClip.stop();
        }
    }

    @Override
    public void run() {
        try {
            while (playing && iterator.hasNext()) {
                Song s = iterator.current();
                playSong(s);

                while (currentClip != null && currentClip.getFramePosition() < currentClip.getFrameLength()) {
                    if (next || previous || stop) break;
                    Thread.sleep(50);
                }

                if (next) {
                    next = false;
                    if (iterator.hasNext()) iterator.next();
                } else if (previous) {
                    previous = false;
                    if (iterator.hasPrevious()) iterator.previous();
                } else if (stop) {
                    stop = false;
                    playing = false;
                    iterator.first();
                    currentClip = null;
                    return;
                } else {
                    if (iterator.hasNext()) iterator.next();
                }
            }
        } catch (Exception e) {
            System.out.println("Erro no player");
        }
    }

    private void playSong(Song s) {
        try {
            AudioInputStream audioStream =
                AudioSystem.getAudioInputStream(new File(s.getFilePath()));
            currentClip = AudioSystem.getClip();
            currentClip.open(audioStream);
            System.out.println("Tocando: " + s.getTitle());
            currentClip.start();
        } catch (Exception e) {
            System.out.println("Erro ao tocar: " + s.getTitle() + " - " + e.getMessage());
        }
    }
}
