local playerManager = require("playerManager")

local textFiles = require("scripts/textFiles")

local battleGeneral,battlePlayer
local onlinePlay

local battleLoadscreen = {}


local NEXT_LEVEL_FILENAME_ADDR = 0x00B25720


battleLoadscreen.dataFilePath = "loadscreenData.txt"


local function getPlayerGroups()
    -- battleGeneral.gameData.decidedPlayerTeams

    -- Local battle
    if onlinePlay.currentMode == onlinePlay.MODE_OFFLINE then
        return {}
    end

    -- Team battle
    if battleGeneral.gameData.teamsEnabled then
        local groups = {}

        for team = 1,2 do
            local group = {name = textFiles.loadscreen.teamNames[team],nameColor = battleGeneral.teamColors[team]}

            for _,user in ipairs(onlinePlay.getUsers()) do
                if battleGeneral.gameData.decidedPlayerTeams[user.playerIdx] == team then
                    table.insert(group,user)
                end
            end

            table.insert(groups,group)
        end

        return groups
    end

    -- Normal battle
    if onlinePlay.getUserCount() >= 6 then
        -- For larger player counts, split it up into two sides
        local leftGroup = {name = "",nameColor = Color.white}
        local rightGroup = {name = "",nameColor = Color.white}

        local splitIndex = math.ceil(onlinePlay.getUserCount()*0.5)

        for userIndex,user in ipairs(onlinePlay.getUsers()) do
            if userIndex > splitIndex then
                table.insert(rightGroup,user)
            else
                table.insert(leftGroup,user)
            end
        end

        return {leftGroup,rightGroup}
    else
        -- For smaller player counts, use one long list
        local group = {name = "",nameColor = Color.white}

        for _,user in ipairs(onlinePlay.getUsers()) do
            table.insert(group,user)
        end

        return {group}
    end
end


function battleLoadscreen.onExitLevel()
    local f = io.open(Misc.episodePath().. battleLoadscreen.dataFilePath,"w")

    if f == nil then
        return
    end

    local nextLevelFilename = readmem(NEXT_LEVEL_FILENAME_ADDR,FIELD_STRING)
    local folderName = nextLevelFilename:match("^(.+)%.lvlx?$") or nextLevelFilename

    local levelConfig = battleGeneral.loadLevelConfig(nextLevelFilename,Misc.episodePath().. folderName.. "/")

    if levelConfig ~= nil and nextLevelFilename ~= battleGeneral.hubLevelFilename and #levelConfig.modeList > 0 then
        f:write(folderName.. "\n")

        -- Level data
        f:write(levelConfig.name.. "\n")
        f:write(textFiles.funcs.replace(textFiles.loadscreen.authorFormat,{NAME = levelConfig.author}).. "\n")

        if battleGeneral.gameData.mode == nil or not levelConfig.modeMap[battleGeneral.gameData.mode] then
            f:write(levelConfig.modeList[1].. "\n")
        else
            f:write(battleGeneral.gameData.mode.. "\n")
        end

        -- Players
        local groups = getPlayerGroups()

        f:write(tostring(#groups).. "\n")

        for _,group in ipairs(groups) do
            f:write(group.name.. "\n")
            f:write(tostring(group.nameColor).. "\n")

            f:write(tostring(#group).. "\n")

            for _,user in ipairs(group) do
                local userData = onlinePlay.getUserData(user.playerIdx)

                local character = battleGeneral.gameData.playerCharacters[user.playerIdx] or CHARACTER_MARIO
                local costumeList = battleGeneral.gameData.playerCostumes[user.playerIdx]
                local costumeName = ""

                if costumeList ~= nil then
                    costumeName = costumeList[character] or ""
                end

                f:write(userData.username.. "\n")
                f:write(tostring(battleGeneral.playerColors[userData.colorIdx]).. "\n")
                f:write(playerManager.getName(character).. "\n")
                f:write(costumeName.. "\n")
            end
        end
    end

    f:close()
end


function battleLoadscreen.onInitAPI()
    registerEvent(battleLoadscreen,"onExitLevel","onExitLevel",false)

    battleGeneral = require("scripts/battleGeneral")
    battlePlayer = require("scripts/battlePlayer")
    onlinePlay = require("scripts/onlinePlay")
end


return battleLoadscreen