/**
 * Created on Oct 31, 2004
 *
 * Copyright (c) Hans-Christoph Steiner
 *
 * 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 2
 * of the License, or (at your option) any later version.
 *
 * See file LICENSE for further informations on licensing terms.
 *
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package typist;

import com.softsynth.jsyn.*;


/**
 * @author hans
 */
public class SquareOscillatorSynthNote extends SynthNote {

    private SquareOscillator mySquareOscillator;

    private SynthEnvelope mySynthEnvelope;

    private EnvelopePlayer myEnvelopePlayer;

    private SynthInput rate;

    public SquareOscillatorSynthNote() {
        add(mySquareOscillator = new SquareOscillator());
        add(myEnvelopePlayer = new EnvelopePlayer());

        // connect unit generators
        myEnvelopePlayer.output.connect(mySquareOscillator.amplitude);
        
        // INPUTS
        addPort(frequency = mySquareOscillator.frequency);
        frequency.setup(16.0, 440, 4186.0);

        addPort(amplitude = myEnvelopePlayer.amplitude);
        amplitude.setup(0.0, 0.0, 1.0);

        addPort(rate = myEnvelopePlayer.rate, "Envelope Rate");
        rate.setup(-15, 5, 15);

        // OUTPUT
        addPort(output = mySquareOscillator.output);
        buildEnvelope();
    }

    void buildEnvelope() throws SynthException {
        double[] data = {
        // duration, value pairs
                0.05, 0.5, 
			   0.001, 0.1, 
			   0.06, 1.0, 
			   0.50, 0.5, 
			   0.50, 0.1, 
			   5.50, 0.0, 
			   0.01, 0.0 
        };

        mySynthEnvelope = new SynthEnvelope(data);
    }

    public void setStage(int time, int stage) throws SynthException {
        switch (stage) {
        case 0:
            start(time);
            myEnvelopePlayer.envelopePort.clear(time);
            myEnvelopePlayer.envelopePort.queue(time, mySynthEnvelope, 0,
                    mySynthEnvelope.getNumFrames(), Synth.FLAG_AUTO_STOP);
            break;
        case 1:
            myEnvelopePlayer.envelopePort.clear(time);
            // queues up a release jump using the last frame of the envelope
            myEnvelopePlayer.envelopePort
                    .queue(time, mySynthEnvelope, mySynthEnvelope
                            .getNumFrames() - 1, 1, Synth.FLAG_AUTO_STOP);
            break;
        default:
            break;
        }
    }
}
