import tjaParser, { Bar, Branch, Course } from 'tja-parser'

export function parseTja(tja: string): Partial<Record<'oni' | 'edit', Course>> {
    const song = tjaParser.Song.parse(tja);

    let oni: Course | undefined = undefined;
    let edit: Course | undefined = undefined;

    if (song.course?.oni) {
        const noteGroups = song.course.oni.noteGroups;
        oni = song.course.oni;
        oni.noteGroups = []

        for (const noteGroup of noteGroups) {
            if (noteGroup instanceof Bar) {
                oni.pushNoteGroups(noteGroup)
            }
            else if (noteGroup instanceof Branch) {
                const bar = noteGroup.master || noteGroup.advanced || noteGroup.normal;
                if (bar) {
                    oni.pushNoteGroups(...bar)
                }
            }
        }
    }
    if (song.course?.edit) {
        const noteGroups = song.course.edit.noteGroups;
        edit = song.course.edit;
        edit.noteGroups = []

        for (const noteGroup of noteGroups) {
            if (noteGroup instanceof Bar) {
                edit.pushNoteGroups(noteGroup)
            }
            else if (noteGroup instanceof Branch) {
                const bar = noteGroup.master || noteGroup.advanced || noteGroup.normal;
                if (bar) {
                    edit.pushNoteGroups(...bar)
                }
            }
        }
    }

    return { oni, edit }
}