/*
 * 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.BufferedInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;

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

    private static AudioInputStream audioInputStream;

    /**
     *
     * @param audio URL, File, InputStream ou String
     * @throws br.com.ctecinf.jetty.audio.AudioException
     */
    public AudioStream(Object audio) throws AudioException {
        try {
            if (audio == null) {
                throw new AudioException("Audio nulo.");
            } else if (audio instanceof String) {
                audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(audio.toString().trim())));
            } else if (audio instanceof File) {
                audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream((File) audio)));
            } else if (audio instanceof InputStream) {
                audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream((InputStream) audio));
            } else if (audio instanceof URL) {
                audioInputStream = AudioSystem.getAudioInputStream((URL) audio);
            } else {
                throw new AudioException("Objeto de audio inválido, somente [File, InputStream, URL, String] são aceitos.");
            }
        } catch (IOException | UnsupportedAudioFileException ex) {
            throw new AudioException("Audio inválido, formato não suportado.");
        }
    }

    /**
     *
     * @return AudioInputStream
     */
    public AudioInputStream getAudioInputStream() {
        return audioInputStream;
    }

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