local MakePlayerCharacter = require "prefabs/player_common"

local assets = {
	Asset( "SCRIPT", "scripts/prefabs/player_common.lua"),
    Asset( "SOUND", "sound/wendy.fsb"),	
    Asset( "ANIM", "anim/miotan.zip" ),
    Asset( "ANIM", "anim/ghost_miotan_build.zip" ),
}

local prefabs = {}

local start_inv = 
	{
		"nightmarefuel",
		"nightmarefuel",
		"nightmarefuel",
		"nightmarefuel"
	}

local function onupdate(inst, dt)
	inst.boost_time = inst.boost_time - dt
	if inst.boost_time <= 0 then
		inst.boost_time = 0
		if inst.boosted_task ~= nil then
			inst.boosted_task:Cancel()
			inst.boosted_task = nil
		end
		inst.components.locomotor.runspeed = TUNING.WILSON_RUN_SPEED
	else
		inst.components.locomotor.runspeed = TUNING.WILSON_RUN_SPEED*1.25
	end
end

local function onlongupdate(inst,dt)
	inst.boost_time = math.max(0,inst.boost_time - dt)
end

local function startboost(inst,duration)
	inst.boost_time = duration
	if inst.boosted_task == nil then
		inst.boosted_task = inst:DoPeriodicTask(1, onupdate, nil, 1)
		onupdate(inst,0)
	end
end

local function onload(inst,data)
	if data ~= nil and data.boost_time ~= nil then
		startboost(inst,data.boost_time)
	end
end

local function onsave(inst,data)
	data.boost_time = inst.boost_time > 0 and inst.boost_time or nil
end


local function oneat(inst,food)
	if food and food.components.edible and food.prefab == "nightmarefuel" then
		inst.SoundEmitter:PlaySound("dontstarve/common/nightmareAddFuel")
		startboost(inst,180)
	end
end

local function onbecameghost(inst)
	if inst.boosted_task ~= nil then
		inst.boosted_task:Cancel()
		inst.boosted_task = nil
		inst.boost_time = 0
	end
end

local common_postinit = function(inst)
    inst.soundsname = "wendy"
	inst:AddTag("miotan")
    inst:AddTag("reader")
	-- Minimap icon
	inst.MiniMapEntity:SetIcon("miotan.tex")
end

-- This initializes for the host only
local master_postinit = function(inst)
	inst.boost_time = 0
	inst.boosted_task = nil

    inst:AddComponent("reader")

	inst.components.hunger.max = 100
	inst.components.sanity.max = 100
	inst.components.health.maxhealth = 100
	inst.components.hunger:DoDelta(0)
	inst.components.sanity:DoDelta(0)
	inst.components.health:DoDelta(0)

	inst.components.sanity.dapperness = -3/54
    inst.components.sanity.night_drain_mult = -TUNING.WENDY_SANITY_MULT
	inst.components.sanity.neg_aura_mult = TUNING.WENDY_SANITY_MULT

	inst.components.eater:SetCanEatNightmareFuel()
	inst.components.eater:SetOnEatFn(oneat)
	inst.components.eater.stale_hunger = -.167
	inst.components.eater.stale_health = 0
	inst.components.eater.spoiled_hunger = -.333
	inst.components.eater.spoiled_health = -.25

    inst:ListenForEvent("ms_becameghost", onbecameghost)
	inst.OnLongUpdate = onlongupdate
	inst.OnSave = onsave
	inst.OnLoad = onload
end

return MakePlayerCharacter("miotan", prefabs, assets, common_postinit, master_postinit, start_inv)
