package vermilion;

// TODO: Look at the loop delay machine and try to work out how to make its delay
// correct under any scenario. This will involve changing machine outputs into
// ringbuffers and knowing processing call sample counts over time. (This is a
// buffering/concurrency thought experiment, contact me).

/**
 * A delay machine which is meant to compensate for the lag when machines are
 * connected in a loop.
 */
public class MachineLoopDelay extends MachineBase
{
    /**
     * The type for this machine is 'EFFECT'.
     */
    @Override
    public String getType()
    {
        return "EFFECT";
    }

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

    private int buffSize;
    private float[][] ringBuffer;
    private ParameterSlider delay;
    private int ringPos = 0;

    /**
     * The mixing algorithm for this plugin simply copies the
     * 'A' buffer to the ring buffer and the ring buffer to the output.
     */
    @Override
    public void fillBuffer(int numSamples)
    {
        int offset = (int) (Main.audio.sampleRate * (delay.value/9999.0f));
        offset = offset - offset%2;

        for (int x = 0; x < numSamples; x++)
        {
            ringBuffer[0][(ringPos + x) % buffSize] = aInput[0][x] * 0.8f;
            ringBuffer[1][(ringPos + x) % buffSize] = aInput[1][x] * 0.8f;
            output[0][x] = ringBuffer[0][(ringPos + x - offset + buffSize) % buffSize];
            output[1][x] = ringBuffer[1][(ringPos + x - offset + buffSize) % buffSize];
        }

        ringPos += numSamples * Main.audio.NUM_CHANNELS;
        ringPos %= buffSize;
    }

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

    /**
     * This machine creates one parameter and a ringbuffer for the delay.
     */
    @Override
    public void setupMachine()
    {
        buffSize = Main.audio.sampleRate * 8;
        ringBuffer = new float[Main.audio.NUM_CHANNELS][buffSize];

        parameters = new ParameterBase[1];

        delay = new ParameterSlider("Delay", false);

        parameters[0] = delay;
    }

    /**
     * This machine has one parameter which it prints in seconds.
     */
    @Override
    public String printParameter(ParameterBase p)
    {
        if (p == delay) return "" + (delay.value / 9999.0f);

        return "";
    }
}