import fakeAudioBuffer from './fakeAudioBuffer';
import { ProjectState, SendableProjectState, Track } from '../types';
import concatBuffers from './concatBuffers';

export const toSendable = (projectState: ProjectState) => ({
  ...projectState,
  tracks: projectState.tracks.map((track) => {
    const { audioBuffers, ...otherTrackProperties } = track;
    const channels = [];
    const audioBuffer = concatBuffers(audioBuffers);
    for (let i = 0; i < audioBuffer.numberOfChannels; i ++) {
      channels.push(audioBuffer.getChannelData(i));
    }
    return {
      ...otherTrackProperties,
      channels
    }
  })
});

export const fromSendable = (sendableProjectState: SendableProjectState) => ({
  ...sendableProjectState,
  tracks: sendableProjectState.tracks
    .filter((track) => track.channels[0].length > 0)
    .map((track): Track => {
      const { channels, ...otherTrackProperties } = track;
      const audioBuffer = fakeAudioBuffer({
        numberOfChannels: channels.length,
        length: channels[0].length,
        sampleRate: sendableProjectState.sampleRate
      });
      channels.forEach((channel, index) => {
        audioBuffer.getChannelData(index).set(channel)
      })
      return {
        ...otherTrackProperties,
        audioBuffers: [audioBuffer]
      };
    })
});
