-----------------------------------
--This file modifies the loadouts UI with BtA specific changes
-----------------------------------

(function()

    local topics = require('lib_ui_topics')
    --local bta = require('btafunctions')
    local utils = require('lib_utils')
    local btaloadouts = require('btaloadouts')

    --For BtA2 missions we show the Loki but don't allow it to be selected
    topics.shipselect.poolentry:bind(1, function(message, context)
        context.value = true

        --Get the blocked list
        if mn.hasCustomData() and mn.CustomData["ShipLoadoutBlocked"] then
            local list = utils.parseCommaSeparatedList(mn.CustomData["ShipLoadoutBlocked"]:gsub('^%((.+)%)$', '%1'))

            --If the list is default then bail
            if list[1]:gsub('^"(.+)"$', '%1') == "none" then
                return
            end

            --If we don't have custom strings then bail
            if not mn.hasCustomStrings() then
                return
            end

            local strings = mn.CustomStrings

            -- Iterate through the values table two steps at a time to create our pairs
            local sets = {}
            for i = 1, #list - 1, 2 do
                local entry = {}
                entry.Ship = list[i]:gsub('^"(.+)"$', '%1')

                --Get the custom string reason
                local text = nil
                local stringName = nil
                if list[i + 1] then
                    stringName = list[i + 1]:gsub('^"(.+)"$', '%1')
                end
                for _, v in pairs(strings) do
                    if v.Name == stringName then
                        text = ba.XSTR(v.String, v.Value)
                        break
                    end
                end

                entry.Reason = text

                if entry.Reason ~= nil then
                    table.insert(sets, entry)
                end
            end

            for i = 1, #sets do
                if message[3].Name == sets[i].Ship then
                    -- Force it to use the grey icon set
                    message[2]:SetAttribute("src", message[3].GeneratedIcon[5])
                    message[3].GeneratedIcon[1] = message[3].GeneratedIcon[5]
                    message[3].GeneratedIcon[3] = message[3].GeneratedIcon[6]

                    -- Add some text overlay
                    local tool_el = message[1].Document:CreateElement("div")
                    tool_el.style.position = "absolute"
                    tool_el.style.width = "200%"
                    tool_el.style.top = "0%"
                    tool_el.style.left = "-75%"
                    tool_el.style.overflow = "visible"
                    tool_el.style["text-align"] = "center"
                    tool_el.style.color = "white"
                    tool_el.inner_rml = "<span class=\"tooltiptext\">" .. sets[i].Reason .. "</span>"
                    message[2]:AppendChild(tool_el)

                    -- Not draggable
                    context.value = false
                end
            end
        end
    end)

    --On Loadouts Init we initialize the countermeasure setup
    topics.loadouts.initialize:bind(1, function(message, context)
        btaloadouts:initCountermeasureSlots()
    end)

    --On Loadouts Unload we clear the countermeasure setup
    topics.loadouts.unload:bind(1, function(message, context)
        --Here 'message' represents commit or cancel. We only clear on cancel or
        --the script won't be able to actually set the countermeasures on mission start
        if message == false then
            btaloadouts:unloadCountermeasureSlots()
        end
    end)

    --When deciding to apply a saved loadout, check if backstock was updated first
    topics.loadouts.rejectSavedLoadout:bind(1, function(message, context)
        if Backstock.updated == true and mn.isInCampaign() then --If the player updated their inventory
            Backstock.updated = nil
            context.value = true
        elseif CustomCheats.loadoutUpdated == true then --If cheats were used to add an easter egg ship
            CustomCheats.loadoutUpdated = nil
            context.value = true
        end
    end)


    --When initializing the loadout pool, Check Inventory availability of all the ships
    topics.loadouts.initPool:bind(1, function(message, context)
        if mn.isInCampaign() and string.sub(mn.getMissionFilename(), 1, 4) == "bta2" then --If no custom data then we assume active
            if (mn.hasCustomData() and string.lower(mn.CustomData["UseInventory"]) ~= "false") or not mn.hasCustomData() then
                btaloadouts:applyInventoryLimits()
            end
        end
    end)

    --When saving the loadout to the file, maybe add the current countermeasure selection
    topics.loadouts.saveLoadout:bind(1, function(message, context)
        if BtACustomLoadouts["countermeasures"] ~= nil then
            message["BtACountermeasures"] = BtACustomLoadouts["countermeasures"]
        end
    end)

    --When viewing a countermeasure set it's data as something actually useful
    topics.weaponselect.entryInfo:bind(999, function(message, context)
        local weapon = message[1]
        local parent_el = message[2]
        local document = parent_el.owner_document

        local class = tb.WeaponClasses[weapon.Index]

        local function format_effectiveness(eff)
            local symbol_count = math.floor(eff / 0.2)  -- Every 0.2 gives one '+'
            return string.rep("+", symbol_count)
        end

        local aspect = class.aspectEffectiveness
        local heat = class.heatEffectiveness
        local range = class.effectiveRange

        if class:isCountermeasure() then
            ScpuiSystem:clearEntries(parent_el)

            local desc_el = document:CreateElement("p")
            desc_el.inner_rml = weapon.Description
            desc_el:SetClass("white", true)

            local stats1a_el = document:CreateElement("p")
            stats1a_el.inner_rml = ba.XSTR("Aspect Effectiveness", 11455) .. ": " .. format_effectiveness(aspect)
            stats1a_el:SetClass("green", true)
            local stats1b_el = document:CreateElement("p")
            stats1b_el.inner_rml = ba.XSTR("Heat Effectiveness", 11456) .. ": " .. format_effectiveness(heat)
            stats1b_el:SetClass("green", true)

            local stats2_el = document:CreateElement("p")
            stats2_el:SetClass("info", true)
            stats2_el:SetClass("red", true)
            stats2_el.inner_rml = ba.XSTR("Range", 11457) .. ": " .. range .. "m"

            local stats3_el = document:CreateElement("p")
            stats3_el:SetClass("info", true)
            stats3_el.inner_rml = ba.XSTR("Cargo Size", 11633) .. ": " .. weapon.CargoSize .. ", " .. ba.XSTR("Rate of Fire", 11634) .. ": " .. weapon.RoF .. "/s"
            stats3_el:SetClass("blue", true)

            parent_el:AppendChild(desc_el)
            parent_el:AppendChild(stats1a_el)
            parent_el:AppendChild(stats1b_el)
            parent_el:AppendChild(stats2_el)
            parent_el:AppendChild(stats3_el)
        end
    end)

    --When loading the loadout from the file, maybe grab the countermeasure data and load it, too
    topics.loadouts.loadLoadout:bind(1, function(message, context)
        if message["BtACountermeasures"] ~= nil then
            BtACustomLoadouts["countermeasures"] = message["BtACountermeasures"]
        end
    end)

    --When emptying a ship slot, also empty the countermeasures
    topics.loadouts.emptyShipSlot:bind(1, function(message, context)
        btaloadouts:EmptyCountermeasureSlot(message)
    end)

    --When filling a ship slot, set countermeasure to default
    topics.loadouts.fillShipSlot:bind(1, function(message, context)
        btaloadouts:SetDefaultCountermeasure(message)
    end)

    --When emptying a ship slot, also empty the countermeasures
    topics.loadouts.returnShipSlot:bind(1, function(message, context)
        btaloadouts:EmptyCountermeasureSlot(message)
    end)

    --When copying a ship slot, copy the countermeasure slot if possible
    topics.loadouts.copyShipSlot:bind(1, function(message, context)
        local sourceCM = btaloadouts:GetCountermeasure(message[1])
        if btaloadouts:isCountermeasureAllowed(message[2], sourceCM) then
            btaloadouts:SetCountermeasure(message[2], sourceCM)
        end
    end)

    --Create the countermeasure dropdown
    topics.weaponselect.initialize:bind(1, function(message, context)

        local parent = message.Document:GetElementById("ship_view_wrapper")

        local lock_el = message.Document:CreateElement("div")
        lock_el.id = "countermeasure_lock"
        lock_el.style.position = "absolute"
        lock_el.style.right = "-1%"
        lock_el.style.bottom = "-10%"
        lock_el.style.width = "42%"
        lock_el.style.height = "10%"
        lock_el.style["z-index"] = "10"

        local select_el, ship_select_el, data_el = btaloadouts:createDropdown(message, ba.XSTR("Countermeasures", 9289))
        select_el.id = "countermeasure_select"
        select_el.style.position = "absolute"
        select_el.style.right = "0%"
        select_el.style.bottom = "-10%"
        select_el.style.width = "40%"

        data_el:AddEventListener("change", function(_, _, _)
            btaloadouts:ChangeCountermeasure(message)
        end)

        data_el:AddEventListener("click", function(_, _, _)
            btaloadouts:ShowCountermeasure(message)
        end)

        parent:AppendChild(lock_el)
        parent:AppendChild(select_el)

        --Hide the countermeasure selector if we're not in BtA2 or the test mission
        if string.sub(mn.getMissionFilename(), 1, 6) ~= "bta2_m" and mn.getMissionFilename() ~= "bta_ship_test" then
            select_el:SetClass("hidden", true)
        end
    end)

    topics.weaponselect.selectShip:bind(1, function(message, context)
        message[1].shipChange = true
        btaloadouts:BuildCountermeasureList(message[1], message[2])
        btaloadouts:SetCountermeasureDropdown(message[1])
        message[1].shipChange = nil
    end)

end)()