// Twink's gift and general upgrade stuff
// Weightedrandom function by Golden

local function weightedRandom(weights)
    local total = 1
    for i, v in ipairs(weights) do
        total = $ + v
    end

    local random = P_RandomRange(1, total)

    total = 1
    for i, v in ipairs(weights) do
        total = $ + v

        if total > random then
            return i
        end
    end

    return #weights
end

local range = FRACUNIT
local weights = {(35*range)/100, (35*range)/100, (30*range)/100}

local effects = {
	function(p) 
		p.InstantTeleportUpgrade = true 
		p.DirectionTeleportUpgrade = false
		p.MultiTeleportUpgrade = false
		print("Instant Teleport!")
	end,
	function(p) 
		p.MultiTeleportUpgrade = true
		p.InstantTeleportUpgrade = false
		p.DirectionTeleportUpgrade = false
		print("Multi-Teleport!")
	end,
	function(p)
		p.DirectionTeleportUpgrade = true 
		p.MultiTeleportUpgrade = false
		p.InstantTeleportUpgrade = false
		print("Direction Teleport!")
	end,
}

local function A_DiceRoll(player)
	local diceroll = weightedRandom(weights)
	effects[diceroll](player)
end

local function initializeGiftVars(p)
	p.Twinksgifttimer = 0
	p.Twinksgiftcooldown = false
	p.InstantTeleportUpgrade = false
	p.MultiTeleportUpgrade = false
	p.DirectionTeleportUpgrade = false
end

addHook("PlayerThink", function(p)
    if not p.mo or not p.mo.valid
	or p.playerstate == PST_DEAD or p.playerstate == PST_REBORN
    or p.mo.skin ~= "paperpeach" return end
	
	if p.Twinksgifttimer == nil then
		initializeGiftVars(p)
	end
	
    if P_IsObjectOnGround(p.mo)
	and (p.cmd.buttons & BT_CUSTOM1)
	and p.mo.momy <= 2*FRACUNIT
	and p.Twinksgiftcooldown == false then
		p.mo.state = S_PPEACH_WISH
		P_SpawnMobjFromMobj(p.mo, 0, 0, 0, MT_TWINK)
		p.Twinksgiftcooldown = true
	end
	if p.mo.state == S_PPEACH_WISH
	or p.mo.state == S_PPEACH_GRANT_START
	or p.mo.state == S_PPEACH_GRANT then
		p.pflags = $1|PF_FULLSTASIS
	end
	if p.mo.state == S_PPEACH_GRANT_START then
		S_StartSound(p.mo, sfx_grant)
		effects[weightedRandom(weights)](p)
	end
	if p.Twinksgiftcooldown == true then
		p.Twinksgifttimer = $+1
	end
	
	if p.Twinksgifttimer == 1225 then
		p.Twinksgifttimer = 0
		p.Twinksgiftcooldown = false
	end
end)
addHook("MobjThinker", function(MT_TWINK)
    if MT_TWINK.state == S_TWINK_APPEAR_START
	or MT_TWINK.state == S_TWINK_DISAPPEAR_START then
		P_SpawnMobjFromMobj(MT_TWINK, 0, 0, 0, MT_TWINK_SPARKLE)
	end
end)

addHook("PlayerThink", function(p)
	if not p.mo or not p.mo.valid
	or p.playerstate == PST_DEAD or p.playerstate == PST_REBORN
	or p.mo.skin ~= "paperpeach" then
		p.Twinksgifttimer = 0
		p.Twinksgiftcooldown = false
		p.InstantTeleportUpgrade = false
		p.MultiTeleportUpgrade = false
		p.DirectionTeleportUpgrade = false
	end
end)