import { ArrayMultimap } from "@opendaw/lib-std";
import { EventSpan, PPQN } from "@opendaw/lib-dsp";
import { ControlEvent, ControlType, MidiFile, MidiTrack } from "@opendaw/lib-midi";
import { Promises } from "@opendaw/lib-runtime";
import { Files } from "@opendaw/lib-dom";
export var NoteMidiExport;
(function (NoteMidiExport) {
    NoteMidiExport.fromCollection = (collection) => {
        const events = [];
        const toTicks = (position, timeDivision = 96) => Math.floor(position / PPQN.Quarter * timeDivision);
        for (const event of collection.asArray()) {
            events.push(new ControlEvent(toTicks(event.position), ControlType.NOTE_ON, event.pitch, Math.round(event.velocity * 127)));
            events.push(new ControlEvent(toTicks(EventSpan.complete(event)), ControlType.NOTE_OFF, event.pitch, 0));
        }
        return new MidiTrack(new ArrayMultimap([[0, events]], ControlEvent.Comparator), []);
    };
    NoteMidiExport.toFile = async (collection, suggestedName = "notes.mid") => {
        const encoder = MidiFile.encoder();
        encoder.addTrack(NoteMidiExport.fromCollection(collection.events));
        return Promises.tryCatch(Files.save(encoder.encode().toArrayBuffer(), {
            types: [{
                    description: "Midi File",
                    accept: { "application/octet-stream": [".mid", ".midi"] }
                }], suggestedName
        }));
    };
})(NoteMidiExport || (NoteMidiExport = {}));
