require "prefabutil"

local Assets=
{
	Asset("ANIM", "anim/moondumplings.zip"),
	Asset("ATLAS", "images/inventoryimages/moondumplings.xml"),
	Asset("ATLAS", "images/inventoryimages/moondumplings_evil.xml")
}

local function onpickup(inst)
end


local function BecomeBunny(inst)
	if not inst.isbunny then
	inst:SetStateGraph("SGmoondumplings")
	inst.sg:GoToState("item")
	inst.isbunny = true
	inst:RemoveTag("evilmoon")
	inst:StopBrain()
	
	inst.DynamicShadow:Enable(false)
	
	local light = inst.entity:AddLight()
    light:SetFalloff(0.7)
    light:SetIntensity(.5)
    light:SetRadius(0.5)
    light:SetColour(237/255, 237/255, 209/255)
    light:Enable(true)
    inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
	end
end

local function BecomeBeardling(inst)
	if inst.isbunny then
	inst:SetStateGraph("SGmoondumplings")
	inst.sg:GoToState("idle")
	inst.isbunny = false
	inst:AddTag("evilmoon")
	inst:RestartBrain()
	
	inst.DynamicShadow:Enable(true)
	
	local light = inst.entity:AddLight()
    light:SetFalloff(0.7)
    light:SetIntensity(.5)
    light:SetRadius(0.5)
    light:SetColour(237/255, 237/255, 209/255)
    light:Enable(false)
    inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
	end
end

local function CheckTransformState(inst)
		local player = GetPlayer()
		if player.components.sanity:GetPercent() > TUNING.BEARDLING_SANITY then
			if GetClock():IsNight() and GetClock():GetMoonPhase() == "full" then
			BecomeBeardling(inst)
			else BecomeBunny(inst)
			end
		else
			BecomeBeardling(inst)			
		end
	end

local function moon_oneaten(inst, eater)

    if eater.wormlight then
        eater.wormlight.components.spell.lifetime = 0
        eater.wormlight.components.spell:ResumeSpell()
    else
        local light = SpawnPrefab("wormlight_light")
        light.components.spell:SetTarget(eater)
        if not light.components.spell.target then
            light:Remove()
        end
        light.components.spell:StartSpell()
    end
end

local function ondrop(inst)
	CheckTransformState(inst)
end

local function OnWake(inst)
	CheckTransformState(inst)
	inst.checktask = inst:DoPeriodicTask(5, CheckTransformState)
end

local function OnSleep(inst)
	 if inst.checktask then
	 	inst.checktask:Cancel()
	 	inst.checktask = nil
	 end
end

local function OnNear(inst)
	if inst:HasTag("evilmoon") then
	local player = GetPlayer()
	player.components.leader:AddFollower(inst)
	else
    end
end

local function OnFar(inst)
    if inst:HasTag("evilmoon") then
    inst.components.follower:SetLeader(nil)
	else
    end
end

local function fn(Sim)
	local inst = CreateEntity()
	 inst.entity:AddSoundEmitter()
	 inst.entity:AddTransform()
	 inst.entity:AddAnimState()
	 inst.Transform:SetFourFaced()
	 inst.entity:AddDynamicShadow()
	 inst.DynamicShadow:SetSize( 1, .5 )
	 MakeInventoryPhysics(inst)
	-------------------◆[Tag]
	 inst:AddTag("cattoy")
	 inst:AddTag("noauradamage")
	 inst:AddTag("notraptrigger")
	 inst:AddTag("moonfood")
	-------------------◆[AnimState]
	 inst.AnimState:SetBank("moondumplings")
	 inst.AnimState:SetBuild("moondumplings")
	 inst:SetStateGraph("SGmoondumplings")
	 inst.sg:GoToState("item")
	-------------------◆[Tradable]
	 inst:AddComponent("tradable")
	-------------------◆[Edible]
	 inst:AddComponent("edible")
	 inst.components.edible.foodtype = "VEGGIE"
	 inst.components.edible.hungervalue = (25)
	 inst.components.edible.healthvalue = (10)
	 inst.components.edible.sanityvalue = (5)
	 inst.components.edible:SetOnEatenFn(moon_oneaten)
	-------------------◆[Perishable]
	 inst:AddComponent("perishable")
	 inst.components.perishable:SetPerishTime(TUNING.PERISH_SUPERSLOW)
	 inst.components.perishable:StartPerishing()
	 inst.components.perishable.onperishreplacement = "petals"
	-------------------◆[Inventory Item]
	 inst:AddComponent("inventoryitem")
	 inst.components.inventoryitem.atlasname = "images/inventoryimages/moondumplings.xml"
	 inst.components.inventoryitem.canbepickedup = true
	 inst.components.inventoryitem:SetOnPickupFn(function() inst.Light:Enable(false) end)
	 inst.components.inventoryitem:SetOnDroppedFn(function() inst.Light:Enable(true) end)
	local light = inst.entity:AddLight()
    light:SetFalloff(0.7)
    light:SetIntensity(.5)
    light:SetRadius(0.5)
    light:SetColour(237/255, 237/255, 209/255)
    inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" )
	-------------------◆[Inspectable]
	 inst:AddComponent("inspectable")
	-------------------◆[Stackable]
	inst:AddComponent("stackable")
	inst.components.stackable.maxsize = TUNING.STACK_SIZE_SMALLITEM
	-------------------◆[PlayerProx]
	 --inst:AddComponent("playerprox")
	 --inst.components.playerprox:SetDist(30, 30)
	 --inst.components.playerprox:SetOnPlayerNear(OnNear)
	 --inst.components.playerprox:SetOnPlayerFar(OnFar)
	-------------------◆[Follower]
	 inst:AddComponent("follower")
	-------------------◆[Locomotor]
	 inst:AddComponent("locomotor")
	 inst.components.locomotor.walkspeed = 4
	-------------------◆[Brain]
	 local brain = require "brains/moondumplingsbrain"
	 inst:SetBrain(brain)
	 inst:StopBrain()
	-------------------◆[FormChange]
	 inst.data = {}
	 BecomeBunny(inst)
	 CheckTransformState(inst)
	 inst.CheckTransformState = CheckTransformState
	inst.OnEntityWake = OnWake
	inst.OnEntitySleep = OnSleep
	-------------------◆[Save&Load]
	 inst.OnSave = function(inst, data)
        if not inst.isbunny then
			data.isbunny = inst.isbunny
		end
	 end        
	 inst.OnLoad = function(inst, data)
        if data then
				local isbunny = data.isbunny or true
		        if not isbunny then
					BecomeBeardling(inst)
		        end
	    end 
	 end
	-------------------◆
	 return inst
end

local function light_resume(inst, time)
    local percent = time/inst.components.spell.duration
    local var = inst.components.spell.variables
    if percent and time > 0 then
        inst.components.lighttweener:StartTween(inst.light, Lerp(0, var.radius, percent), 0.8, 0.5, {1,1,1}, 0)
        inst.components.lighttweener:StartTween(nil, 0, nil, nil, nil, time)
    end
end

local function light_onsave(inst, data)
    data.timealive = inst:GetTimeAlive()
end

local function light_onload(inst, data)
    if data and data.timealive then
        light_resume(inst, data.timealive)
    end
end

local function light_spellfn(inst, target, variables)
    if target then
        inst.Transform:SetPosition(target:GetPosition():Get())
    end
end

local function light_start(inst)
    local spell = inst.components.spell
    inst.components.lighttweener:StartTween(inst.light, spell.variables.radius, 0.8, 0.5, {169/255,231/255,245/255}, 0)
    inst.components.lighttweener:StartTween(nil, 0, nil, nil, nil, spell.duration)
end

local function light_ontarget(inst, target)
    if not target then return end
    target.wormlight = inst
    target:AddTag(inst.components.spell.spellname)
    target.AnimState:SetBloomEffectHandle("shaders/anim.ksh")
end

local function light_onfinish(inst)
    if not inst.components.spell.target then
        return
    end
    inst.components.spell.target.wormlight = nil
    inst.components.spell.target.AnimState:ClearBloomEffectHandle()
end

local light_variables = {
    radius = TUNING.WORMLIGHT_RADIUS,
}

local function lightfn()

    local inst = CreateEntity()
    inst.entity:AddTransform()

    inst:AddComponent("lighttweener")
    inst.light = inst.entity:AddLight()
    inst.light:Enable(true)

    inst:AddTag("FX")
    inst:AddTag("NOCLICK")
    local spell = inst:AddComponent("spell")
    inst.components.spell.spellname = "wormlight"
    inst.components.spell:SetVariables(light_variables)
    inst.components.spell.duration = 40
    inst.components.spell.ontargetfn = light_ontarget
    inst.components.spell.onstartfn = light_start
    inst.components.spell.onfinishfn = light_onfinish
    inst.components.spell.fn = light_spellfn
    inst.components.spell.resumefn = light_resume
    inst.components.spell.removeonfinish = true

    return inst
end

return
		Prefab("common/inventory/moondumplings", fn, Assets)