package turgen.output;

import java.util.Iterator;
import javax.swing.*;
import turgen.playlist.*;
import turgen.*;
import turgen.generator.*;
import turgen.plugin.*;
import turgen.config.*;

/**Na starosti vystup do WAVE souboru system*/
public class WaveOutput {

    public static ConfigClass cfcWaveOutput;
    public static BooleanConfigEntry cfgWOAutoRenameToWAV;
    
    public static void init() {

        /*Initialize configuration class*/
        cfcWaveOutput = new ConfigClass("WaveOutput","WAVE output");

        /*Initialize configuration entries*/
        cfgWOAutoRenameToWAV= new BooleanConfigEntry("autoRenameToWAV","Change extension to .wav",true);

        /*Add entries to the class*/
        cfcWaveOutput.addEntry(cfgWOAutoRenameToWAV);

        /*Register configuration class*/
        Configuration.registerClass(cfcWaveOutput);
        
    }

    /**Zpracuje polozky playlistu na urcenych indexech*/
    public static synchronized void processPlaylistItems(Iterator<AbstractPlayListItem> items,JComponent[] cmps,TurgenStatus st,boolean postProEnabled) {
        
        ParallelGUIUpdater.setComponentsEnabled(cmps, false);
        
        st.clearWaves();
        
        /*pro kazdou polozku*/
        while(items.hasNext()) {
            AbstractPlayListItem api = items.next();
            /*Zjistit zasuvny modul*/
            Plugin p = Turgen.pluginManager.getPlugin(api.pluginClass);
            /*Kdyz pluginClass neni, tak se pokracuje*/
            if (p==null) {
                ParallelGUIUpdater.showMessage("<HTML>Plugin \""+api.pluginClass+"\" <BR>specified in a playlist item not found.</HTML>");
                st.addFailedWaves();
                continue;
            }

            /*Convert an item and get SignalGenerator instructions*/
            int[] instr;
            try {
                instr = p.convertItem(api);
            }
            catch (Exception e) {
                ParallelGUIUpdater.showMessage(Utils.getTitledExceptionMessage("Conversion failed", e));
                st.addFailedWaves();
                e.printStackTrace();
                continue;
            }
            
            /*Zkusi pustit generator*/
            try {
                SignalGenerator g = new SignalGenerator(api,instr,cfgWOAutoRenameToWAV.getAsBoolean(),postProEnabled,SignalGenerator.TYPE_WAVE);
                
                /*Kazdy generator bezi v samostatnem vlakne*/
                Thread t = new Thread((Runnable)g);
                t.start();
                
            }
            catch(Exception e) {
                /*Ostatni vyjimky nejsou OK*/
                e.printStackTrace();
                ParallelGUIUpdater.showMessage(Utils.getTitledExceptionMessage("WAVE output",e));
            }
            
        }
        
        ParallelGUIUpdater.setComponentsEnabled(cmps, true);
        
    }

}
