-- Lampovo Project ^ω^ Average Enjoyer

AdditionalSellingStations = {}

g_xmlManager:addCreateSchemaFunction(function ()
    AdditionalSellingStations.xmlSchema = XMLSchema.new("addToSellingStation")
end)

local modDir = g_currentModDirectory

local function inj_placeableSellingStation_onLoad(self, superFunc, savegame)
    superFunc(self, savegame)

    local xmlFilename = modDir .. "xml/addToSellingStation.xml"
    local xmlFile = XMLFile.load("mod_addToSellingStationXMLFile", xmlFilename)

    if xmlFile == nil then
        Logging.warning("Could not load addToSellingStation XML: %s", xmlFilename)
        return true
    end

    local spec = self.spec_sellingStation
    local sellingStation = spec and spec.sellingStation
    if sellingStation == nil then
        Logging.warning("SellingStation spec not found on this placeable")
        xmlFile:delete()
        return true
    end

    for _, key in xmlFile:iterator("addToSellingStation.sellingStation") do
        local attachToName = xmlFile:getString(key .. "#attachTo")
        local fillTypesStr = xmlFile:getString(key .. "#fillType")

        if attachToName and fillTypesStr then
            local attachTo = g_fillTypeManager:getFillTypeIndexByName(attachToName:upper())

            if attachTo ~= nil and sellingStation.supportedFillTypes[attachTo] then
                local newFillTypes = fillTypesStr:split(" ")
                for _, fillTypeName in ipairs(newFillTypes) do
                    local fillType = g_fillTypeManager:getFillTypeByName(fillTypeName:upper())
                    if fillType ~= nil and sellingStation.supportedFillTypes[fillType.index] ~= true then
                        sellingStation.supportedFillTypes[fillType.index] = true
                        sellingStation:addAcceptedFillType(fillType.index, fillType.pricePerLiter, true, false)

                        for _, unloadTrigger in pairs(sellingStation.unloadTriggers) do
                            unloadTrigger.fillTypes[fillType.index] = true
                        end

                        Logging.info("[Corn Production Pack] Added fillType '%s' to selling station (attached via '%s')", fillTypeName, attachToName)
                    end
                end
            end
        end
    end

    xmlFile:delete()

    sellingStation:initPricingDynamics()
    sellingStation:updateSupportedFillTypes()

    return true
end

PlaceableSellingStation.onLoad = Utils.overwrittenFunction(PlaceableSellingStation.onLoad, inj_placeableSellingStation_onLoad)