package vermilion;

/**
 * A source machine that produces a 1 kHz test tone with a duty cycle.
 */
public class MachineTestTone extends MachineBase
{
    private ParameterSlider onTime = null;
    private ParameterSlider offTime = null;

    /**
     * The type for this machine is 'SOURCE'.
     */
    @Override
    public String getType()
    {
        return "SOURCE";
    }

    /**
     * The name for this machine is 'Test Tone'.
     */
    @Override
    public String getName()
    {
        return "Test Tone";
    }

    /**
     * This plugin does not require initialisation and does nothing.
     */
    @Override
    public void initialise()
    {
    }

    // A counter so we produce a continuous tone.
    private int sampleNum = 0;
    private boolean on = false;
    private int countDown = 0;

    /**
     * The mixing algorithm for this plugin simply fills the output buffer
     * a sine wave at 1 kHz. The tone is gated by an on/off duty cycle
     * determined by the parameters on the machine.
     */
    @Override
    public void fillBuffer(int numSamples)
    {
        double cycleTime = 1000.0 / Main.audio.sampleRate;
        cycleTime *= Math.PI;

        for (int x = 0; x < numSamples; x++)
        {
            if (countDown <= 0)
            {
                on = !on;

                if (on) countDown = (int) (Main.audio.sampleRate * (onTime.value / 1000.0f));
                else countDown = (int) (Main.audio.sampleRate * (offTime.value / 1000.0f));
            }

            if (on)
            {
                sampleNum++;
                float tone = (float) Math.sin(sampleNum * cycleTime) * 0.2f;
                output[0][x] = tone;
                output[1][x] = tone;
            }
            else
            {
                output[0][x] = 0.0f;
                output[1][x] = 0.0f;
            }

            countDown--;
        }
    }

    /**
     * This machine does nothing on direct parameter changes.
     */
    @Override
    public void parameterChange(PlaybackEvent param)
    {
    }

    /**
     * The setup for this machine creates two parameters.
     */
    @Override
    public void setupMachine()
    {
        parameters = new ParameterBase[2];

        onTime = new ParameterSlider("On Time", false);
        offTime = new ParameterSlider("Off Time", false);

        parameters[0] = onTime;
        parameters[1] = offTime;
    }

    /**
     * This machine prints the values for the parameters in seconds.
     */
    @Override
    public String printParameter(ParameterBase p)
    {
        ParameterSlider s = (ParameterSlider) p;
        String str = String.valueOf(s.value);
        if (str.length() == 1) str = "0.00" + str;
        else if (str.length() == 2) str = "0.0" + str;
        else if (str.length() == 3) str = "0." + str;
        else if (str.length() == 4) str = str.substring(0, 1) + "." + str.substring(1);
        return str;
    }
}