import { Note, NoteLane, ParsedMIDIFile } from './types';

const separateNotes = (file: ParsedMIDIFile) => {
  const result: NoteLane[] = [];
  file.channels.forEach((channel, channelIndex) => {
    channel.instruments.forEach((instrument, instrumentIndex) => {
      const notesByTrack = instrument.notes.reduce((acc, note) => {
        if (!acc[note.sourceTrack]) {
          acc[note.sourceTrack] = [];
        }
        acc[note.sourceTrack].push(note);
        return acc;
      }, {} as { [key: string]: Note[] });
      Object.entries(notesByTrack).forEach(([trackIndex, notes]) => {
        const track = file.tracks[Number(trackIndex)];
        result.push({
          track: Number(trackIndex),
          trackName: track.name,
          channel: channelIndex,
          isDrumIndex: channel.isDrumIndex,
          instrument: instrumentIndex,
          program: instrument.program,
          notes,
        });
      });
    });
  });
  return result;
}

export default separateNotes;
