/*
 * Copyright 2015 Andrew T. Flowers, K0SM.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dopplerpsk.util;

import java.util.Map;
import java.util.TreeMap;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.SourceDataLine;

/**
 *
 * @author Andrew
 */
public class AudioConfiguration {
    
     private static Map<String, Mixer.Info> audioMap = new TreeMap();
    
     public static String[] getMixerNames() {
         return audioMap.keySet().toArray(new String[0]);
     }
     
     public static Mixer.Info getMixerInfoFromName(String name) {
         return audioMap.get(name);
     }
     
     public static void findAudioConfigurations() {
        
        Mixer.Info[] minfoSet = AudioSystem.getMixerInfo();

        //System.out.println("Mixers:");
        for (Mixer.Info minfo : minfoSet) {
            Mixer m = AudioSystem.getMixer(minfo);
            Line.Info[] tlines = m.getSourceLineInfo();
            if (tlines.length > 0) {
                System.out.println("   " + minfo.toString());
                audioMap.put(minfo.toString(), minfo);
                System.out.println("      " + tlines.length + " Source lines:");
                for (Line.Info t : tlines) {
                    System.out.println("        " + t.toString());
                }
            }
        }
    }

    public static SourceDataLine getSourceDataLine(String mixerInfoString, AudioFormat format) throws LineUnavailableException {
        SourceDataLine line = null;

            if (mixerInfoString == null) {
                line = AudioSystem.getSourceDataLine(format);
               
            } else {
                Mixer.Info[] minfoSet = AudioSystem.getMixerInfo();
                for (Mixer.Info minfo : minfoSet) {
                    if (minfo.toString().equals(mixerInfoString)) {
                        line = AudioSystem.getSourceDataLine(format, minfo);
                    }
                }
            }
       
        // if we haven't found it, return the default
        if (line == null) {
            line = AudioSystem.getSourceDataLine(format);
        }
        return line;
    }

}
