local MakePlayerCharacter = require "prefabs/player_common"


local assets = {
    Asset("SCRIPT", "scripts/prefabs/player_common.lua"),
}
local prefabs = {}

-- Custom starting items
local start_inv = {
	
}


-- Rain Checker
local function doraincheck(inst, dt)

    if TheWorld.state.israining then
		inst.components.sanity.dapperness = (-TUNING.DAPPERNESS_LARGE * 1.5)
    
	end
	
end

local easing = require("easing")
local function sanityfn(inst)
	local delta = 0
    if inst.components.moisture then
		delta = easing.inSine(inst.components.moisture:GetMoisture(), 0, TUNING.MOISTURE_SANITY_PENALTY_MAX, inst.components.moisture:GetMaxMoisture())
	end
    return delta * .5
end


-- Afraid of Spiders


local function sanityfn(inst)
	local x,y,z = inst.Transform:GetWorldPosition()	
	local delta = 0
	local max_rad = 20
	local ent = FindEntity(inst, 100, function(ent) 
		return ent:HasTag("spider")
			and not(ent.components.health and ent.components.health:IsDead())
	end)
	
	local ent = FindEntity(inst, 100, function(ent) 
		return ent:HasTag("spider_warrior")
			and not(ent.components.health and ent.components.health:IsDead())
	end)
	
	local ent = FindEntity(inst, 100, function(ent) 
		return ent:HasTag("spiderden")
			and not(ent.components.health and ent.components.health:IsDead())
	end)
	
	
	if ent then
		local sz = -TUNING.SANITYAURA_LARGE*3
		local rad = 20
		sz = sz * ( math.min(max_rad, rad) / max_rad )
		local distsq = inst:GetDistanceSqToInst(ent)
		delta = delta + sz/math.max(1, distsq)
	end
	
	--função da perda de sanidade do tempo - essa é a que funciona.
	if TheWorld.state.isday then delta = delta -0.20
	elseif TheWorld.state.isdusk then delta = delta +0.15
	elseif TheWorld.state.isnight then delta = delta +0.10
	end
    
    return delta
end



-- light sanity loss
--local function sanityfnz(inst)local delta = 0
--if TheWorld.state.isday then delta = -0.25
--elseif TheWorld.state.isdusk then delta = 0.1
--elseif TheWorld.state.isnight then delta = 0.15
--end
--return 
--delta
--end






-- When the character is revived from human
local function onbecamehuman(inst)
	-- Set speed when reviving from ghost (optional)
	inst.components.locomotor.walkspeed = 5.5
	inst.components.locomotor.runspeed = 9.5
end

local function onbecameghost(inst)
	-- Remove speed modifier when becoming a ghost
   inst.components.locomotor:RemoveExternalSpeedMultiplier(inst, "raymond_speed_mod")
end

-- When loading or spawning the character
local function onload(inst)
    inst:ListenForEvent("ms_respawnedfromghost", onbecamehuman)
    inst:ListenForEvent("ms_becameghost", onbecameghost)

    if inst:HasTag("playerghost") then
        onbecameghost(inst)
    else
        onbecamehuman(inst)
    end
end

-- This initializes for both the server and client. Tags can be added here.
 
	-- Minimap icon


-- Sanity loss on attacked by spider
local function onattacked(inst, data)
	if data.attacker and data.attacker:HasTag("spider") then
		inst.components.sanity:DoDelta(-10)
	end
end




-- This initializes for the server only. Components are added here.
local master_postinit = function(inst)




inst:AddComponent("meteorshower")
if inst.components.meteorshower.task then --it automatically scheduled a shower
	inst.components.meteorshower:StopShower() --remove the automatically-scheduled shower
end
--override the StartCooldown on this particular component instance so it does not schedule more showers after completing one
inst.components.meteorshower.StartCooldown = inst.components.meteorshower.StopShower
--Watch sanity to know when to trigger the showers
inst:ListenForEvent("sanitydelta", function(inst, data)
	--data provides the oldpercent and newpercent for sanity, so it is easier to do thresholds in percents
	--... but you could convert like this
	local oldsanity = data.oldpercent * inst.components.sanity.max
	local newsanity = data.newpercent * inst.components.sanity.max
	local level = nil
	if newsanity <= 0 and oldsanity > 0 or newsanity <= 10 and oldsanity > 10 then
    	level = 3
    elseif newsanity <= 20 and oldsanity > 20 then
    	level = 3
    elseif newsanity <= 30 and oldsanity > 30 then
    	level = 3
	elseif newsanity <= 40 and oldsanity > 40 then
    	level = 3
    end
    if level then --we passed a threshold and need to spawn a shower
    	inst.components.meteorshower:StartShower(level)
    end
end)










	-- choose which sounds this character will play
	inst.soundsname = "willow"
	
	-- Remove raw meat penalty
	inst.components.eater.Eat_orig = inst.components.eater.Eat
	function inst.components.eater:Eat( food )
		if food and food.components.edible and food.components.edible.foodtype == FOODTYPE.MEAT and self:CanEat(food) then
			if food.components.edible.sanityvalue < 0 then
				food.components.edible.sanityvalue = 0
			end
			if food.components.edible.healthvalue < 0 then
				food.components.edible.healthvalue = 0
			end
		end
		return inst.components.eater:Eat_orig(food)
	end
	
	-- Stats	
	inst.components.health:SetMaxHealth(100) --Life
	inst.components.hunger:SetMax(80) --Hunger
	inst.components.sanity:SetMax(120) -- Sanity
	inst.components.locomotor.walkspeed = (5.5) --Walk
	inst.components.locomotor.runspeed = (9.5) --Walk on trail
	--inst.components.eater.strongstomach = true --can eat raw meat
	inst.components.eater.monsterimmune = false --can eat monster meat
	--inst.components.eater:SetCarnivore()
	inst.components.temperature.mintemp = ( 10 ) --minimal temperature, never gets cold
	inst.components.health.fire_damage_scale = 2.5
	inst.components.temperature.rate_modifier = 2.5
	inst.components.temperature.overheattemp = 50
	
	inst:ListenForEvent("attacked", onattacked)
	
		inst.components.eater.strongstomach = true
	local caneat = inst.components.eater.caneat
	for i, v in ipairs(caneat) do
        inst:RemoveTag((type(v) == "table" and v.name or v).."_eater")
    end
	inst.components.eater.caneat = {FOODTYPE.MEAT}
	inst.components.eater.preferseating = {FOODTYPE.MEAT}
	inst:AddTag(FOODTYPE.MEAT.."_eater")
	
	if inst.components.moisture then
		inst.components.moisture.maxMoistureRate = inst.components.moisture.maxMoistureRate * 2
		inst.components.moisture.maxPlayerTempDrying = inst.components.moisture.maxPlayerTempDrying * 2
		inst.components.moisture.maxDryingRate = inst.components.moisture.maxDryingRate * 2
	end
	
	-- Damage multiplier (optional)
    inst.components.combat.damagemultiplier = 0.8
	
	-- Hunger rate (optional)
	inst.components.hunger.hungerrate = 0.8 * TUNING.WILSON_HUNGER_RATE
	
	-- light emitter 
		--inst.entity:AddLight()
		--inst.Light:Enable(true)
		--inst.Light:SetRadius(6)
		--inst.Light:SetFalloff(.5)
		--inst.Light:SetIntensity(0.8)
		--inst.Light:SetColour(206/255,139/255,235/255)
	
	
	inst.OnLoad = onload
    inst.OnNewSpawn = onload
	
	-- Custom sanity function
	inst.components.sanity.custom_rate_fn = sanityfn
	
	
end

local function UpdateNightVision(inst, phase)
	local enable = phase == "night"
	inst:DoTaskInTime(enable and 0 or 1, function(inst)
		inst.components.playervision:ForceNightVision(enable)
		inst.components.playervision:SetCustomCCTable(enable and {} or nil)
	end)
end

local function OnInitNightVision(inst)
	if TheWorld.ismastersim or inst.HUD then
		inst:WatchWorldState("phase", UpdateNightVision)
		UpdateNightVision(inst, TheWorld.state.phase)
	end
end

local function common_postinit(inst)
	inst:DoTaskInTime(0, OnInitNightVision)
	inst:AddTag("rabbithunter")
	inst.MiniMapEntity:SetIcon( "raymond.tex" )
	
end

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

