/*
 * Copyright (C) 2025 ctecinf.com.br
 *
 * 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 <http://www.gnu.org/licenses/>.
 */
package br.com.ctecinf.jetty.audio;

import java.io.Closeable;
import java.io.IOException;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;

/**
 *
 * @author Cássio Conceição
 * @since 13/06/2023
 * @version 2503
 * @see http://hobbyslotcar.com.br
 */
public class AudioRunnable implements Closeable, Runnable {

    protected static final int BUFFER_SIZE = 4096;

    private final AudioStream audioStream;
    private SourceDataLine sourceDataLine;

    public AudioRunnable(AudioStream audioStream) {
        this.audioStream = audioStream;
    }

    @Override
    public void run() {
        try (AudioInputStream audioInputStream = audioStream.getAudioInputStream()) {
            sourceDataLine = (SourceDataLine) AudioSystem.getLine(new DataLine.Info(SourceDataLine.class, audioInputStream.getFormat()));
            sourceDataLine.open();
            sourceDataLine.start();
            byte[] bufferBytes = new byte[BUFFER_SIZE];
            int readBytes;
            while ((readBytes = audioInputStream.read(bufferBytes)) > 0) {
                sourceDataLine.write(bufferBytes, 0, readBytes);
            }
            sourceDataLine.drain();
            close();
        } catch (Exception ex) {
            System.err.println(ex);
        }
    }

    /**
     * Pára a execução
     */
    public void stop() {
        if (sourceDataLine != null) {
            sourceDataLine.stop();
        }
    }

    @Override
    public void close() throws IOException {
        if (sourceDataLine != null) {
            sourceDataLine.close();
        }
        sourceDataLine = null;
    }
}
