local minipopup = require("#Celeste.Mod.SorbetHelper.Entities.MiniPopupDisplay")

local session = require("#Celeste.Session")
local scene = session.LevelData


function getCounter(key)
    return engine.Scene.Session:GetCounter(key)
end

function getSlider(key)
    return engine.Scene.Session:GetSlider(key)
end

function setCounter(key, value)
    return engine.Scene.Session:SetCounter(key, value)
end

function setSlider(key, value)
    return engine.Scene.Session:SetSlider(key, value)
end

function makeBuildingAchievements(achtable)
    local nums = {1, 50, 100, 150, 200}
    for e = 1, 10, 1 do
        for i = 1, 5, 1 do
            table.insert(achtable,
                {varName="b"..e.."Count", varType="#", amount=nums[i]}
            )
        end
    end
end

function makeTotalAchievements(achtable)
    local nums = {1, 1000, 100000, 1000000, 100000000, 1000000000, 100000000000, 1000000000000, 100000000000000, 1000000000000000}
    for e = 1, 10, 1 do
        table.insert(achtable, {varName="berriesThisAscension", varType="@", amount=nums[e]})
    end
    local nums = {1, 10, 100, 1000, 10000, 1000000, 10000000, 100000000, 1000000000, 10000000000}
    for e = 1, 10, 1 do
        table.insert(achtable, {varName="scorePerSecond", varType="@", amount=nums[e]})
    end
    local nums = {1, 25, 50, 75, 100}
    for e = 1, 5, 1 do
        table.insert(achtable, {varName="allBuildingCount", varType="#", amount=nums[e]})
    end
end

local achievements = {

}

function evaluateAchievement(ach)
    if not (getFlag("achievement_"..ach.varName.."_"..ach.amount)) and ((ach.varType=="#" and getCounter(ach.varName) >= ach.amount) or (ach.varType=="@" and getSlider(ach.varName) >= ach.amount)) then
       setFlag("achievement_"..ach.varName.."_"..ach.amount, true)
       -- miniTextbox("CommunityVoice_strawsim_".."achievement_"..ach.varName.."_"..ach.amount)
       popup = minipopup()
       local lvl = getLevel()
       lvl:Add(popup)
       popup:CreatePopup(
            2.0, 
            "CommunityVoice_strawsim_unlock", 
            "CommunityVoice_strawsim_".."achievement_"..ach.varName.."_"..ach.amount
        )
       setCounter("numAchievements", getCounter("numAchievements") + 1)
       wait(3)
    end
end

function onBegin()
    local min = 100000000000

    for i = 1, 10, 1 do
        if getCounter("b"..i.."Count") < min then
            min = getCounter("b"..i.."Count")
        end
    end

    setCounter("allBuildingCount", min)

    makeUnskippable()
    makeBuildingAchievements(achievements)
    makeTotalAchievements(achievements)

    for i, v in ipairs(achievements) do
        evaluateAchievement(v)
    end
end

function onEnd()
    
end