-- =====================================================
-- ReaBank Dropdown Selector (Cross Platform)
-- =====================================================

-------------------------------------------------------
-- ReaBank Ordner automatisch finden
-------------------------------------------------------
local resource_path = reaper.GetResourcePath()
local reabank_dir = resource_path .. "/Data"

-------------------------------------------------------
-- ReaBank Dateien sammeln
-------------------------------------------------------
local reabanks = {}

local i = 0
repeat
    local file = reaper.EnumerateFiles(reabank_dir, i)
    if file and file:lower():match("%.reabank$") then
        table.insert(reabanks, file)
    end
    i = i + 1
until not file

if #reabanks == 0 then
    reaper.ShowMessageBox("Keine ReaBank gefunden!", "Fehler", 0)
    return
end

-------------------------------------------------------
-- Dropdown Menü bauen
-------------------------------------------------------
local menu = table.concat(reabanks, "|")

gfx.init("ReaBank wählen", 300, 120)

gfx.x = 10
gfx.y = 10
gfx.drawstr("ReaBank auswählen:")

local retval, choice = gfx.showmenu(menu)
gfx.quit()

if choice < 1 then return end

local selected_bank = reabank_dir .. "/" .. reabanks[choice]

-------------------------------------------------------
-- ReaBank laden
-------------------------------------------------------
reaper.MIDI_LoadBank(selected_bank)

-------------------------------------------------------
-- Bank/Program Eingabe
-------------------------------------------------------
local ok, input = reaper.GetUserInputs(
    "Bank / Program",
    3,
    "Bank MSB (CC0),Bank LSB (CC32),Program",
    "0,0,0"
)

if not ok then return end

local msb, lsb, program = input:match("([^,]+),([^,]+),([^,]+)")

msb = tonumber(msb)
lsb = tonumber(lsb)
program = tonumber(program)

-------------------------------------------------------
-- Selektierten Track holen
-------------------------------------------------------
local track = reaper.GetSelectedTrack(0,0)
if not track then
    reaper.ShowMessageBox("Kein Track ausgewählt!", "Fehler",0)
    return
end

local item = reaper.GetTrackMediaItem(track,0)
if not item then
    reaper.ShowMessageBox("Kein MIDI Item vorhanden!", "Fehler",0)
    return
end

local take = reaper.GetActiveTake(item)
if not take or not reaper.TakeIsMIDI(take) then
    reaper.ShowMessageBox("Kein MIDI Take!", "Fehler",0)
    return
end

-------------------------------------------------------
-- Bank Select + Program Change setzen
-------------------------------------------------------
local ppq = 0

-- CC0 MSB
reaper.MIDI_InsertCC(take,false,false,ppq,0xB0,0,0,msb)

-- CC32 LSB
reaper.MIDI_InsertCC(take,false,false,ppq,0xB0,0,32,lsb)

-- Program Change
reaper.MIDI_InsertEvt(
    take,false,false,ppq,
    string.char(0xC0, program)
)

reaper.MIDI_Sort(take)

reaper.ShowMessageBox("ReaBank zugewiesen!", "Fertig",0)