/*
 * Copyright (C) 2013 Darth Affe <http://wyrez.org> and contributors
 *
 * 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 org.wyrez.audio.decoder;

import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Factory used to create Audio-Decoder.
 *
 * @author Darth Affe
 */
public enum DecoderFactory {

    WAVE, MP3, OGG;

    /**
     * Creates a decoder for the selected codec.
     *
     * @returns The new decoder
     * @throws Exception in case the Decoder could not be created
     */
    public Decoder create(InputStream is) throws Exception {
        switch (this) {
            case MP3:
                return new MP3Decoder(is);
            case OGG:
                return new VorbisDecoder(is);
            case WAVE:
                return new WaveDecoder(is);
            default: //impossible
                return null;
        }
    }

    /**
     * Creates a decoder for the given file, if there isn't one an exception is
     * thrown.
     *
     * @returns The new decoder
     * @throws Exception in case the Decoder could not be created
     * @throws IllegalArgumentException in case there is now decoder for the
     * given file
     */
    public static Decoder create(String file) throws Exception, IllegalArgumentException {
        int i = file.lastIndexOf('.');
        if (i == 0) {
            throw new IllegalArgumentException("Can't detect a filetype");
        }
        String extension = file.substring(i + 1);
        switch (extension.toUpperCase()) {
            case "MP3":
                return MP3.create(new FileInputStream(file));
            case "OGG":
                return OGG.create(new FileInputStream(file));
            case "WAV":
            case "WAVE":
                return WAVE.create(new FileInputStream(file));
            default:
                throw new IllegalArgumentException("Filetype \"" + extension + "\" is not supported.");
        }
    }
}
