package vermilion;

/**
 * This class encapsulates a sample that is currently playing.
 */
public class UtilPlayingNoteSample extends UtilPlayingNote
{
    public int sampleIndex;
    public int envIndex;

    private double playbackRate = 0.0;
    private double playbackPos = 0;

    private float[][] sampleData = null;

    // Since a sample is not complete without a pitch and a sample, the
    // constructor takes no arguments and allows the values to be set later.
    public UtilPlayingNoteSample(int trackNum)
    {
        super(0, trackNum);
    }

    @Override
    void mix(float[][] output, int numSamples)
    {
        if (playbackRate == 0.0)
        {
            SampleSampledAudio smp = ((SampleSampledAudio) MachineBase.sampleBank.getSample(sampleIndex));

            if (smp != null)
            {
                double relPitch = UtilFunctions.notePitch(playbackPitch) / UtilFunctions.notePitch(ParameterNote.MIDDLE_C);
                playbackRate = relPitch * smp.sampleRate / Main.audio.sampleRate;

                sampleData = ((SampleSampledAudio) MachineBase.sampleBank.getSample(sampleIndex)).sampleData;
            }
            else
            {
                isPlaying = false;
                return;
            }
        }

        for (int x = 0; x < numSamples; x ++)
        {
            if (sampleData.length == 1)
            {
                output[0][x] += sampleData[0][(int) playbackPos];
                output[1][x] += sampleData[0][(int) playbackPos];
            }
            else
            {
                output[0][x] += sampleData[0][(int) playbackPos];
                output[1][x] += sampleData[1][(int) playbackPos];
            }

            playbackPos += playbackRate;
            if (playbackPos >= sampleData[0].length)
            {
                playbackPos = sampleData[0].length-1;
                isPlaying = false;
            }
        }
    }
}
