local MakePlayerCharacter = require "prefabs/player_common"

local assets = 
{
	Asset("ANIM", "anim/smallbird_shiny_build_01.zip"),
	Asset("ANIM", "anim/teenbird_shiny_build_01.zip"),
	Asset("ANIM", "anim/tallbird_shiny_build_01.zip"),
}
local prefabs = {	
    }
	
local start_inv = {

}

SetSharedLootTable('smallbirdp',
{
    {"smallmeat", 1.00},
    
})
--local birdfood = 1

foodprefs = {"VEGGIE", "SEEDS"}
food2prefs = {"MEAT", "VEGGIE"}

local function onupdate(inst, dt)
    inst.charge_time = inst.charge_time - dt
    if inst.charge_time <= 0 then
        inst.charge_time = 0
		if inst.charge_task ~= nil then
            inst.charge_task:Cancel()
            inst.charge_task = nil
        end
        inst.specialatk = true
		inst.sg:GoToState("idle_peep")
    else
    --    
    end
end

local function OnLongUpdate(inst, dt)
    inst.charge_time = math.max(0, inst.charge_time - dt)
end

------------------------------------------------------
----PvP Teleport----

local function getwildposition(inst)
    local ground = TheWorld
    local centers = {}
    for i, node in ipairs(ground.topology.nodes) do
        if ground.Map:IsPassableAtPoint(node.x, 0, node.y) then
            table.insert(centers, {x = node.x, z = node.y})
        end
    end
    if #centers > 0 then
        local pos = centers[math.random(#centers)]
        return Point(pos.x, 0, pos.z)
    else
        return inst:GetPosition()
    end
end

local function PvPTeleport(inst)
if inst.mobteleported == nil or inst.mobteleported == false then
	local ground = TheWorld
	local pt = getwildposition(inst)--Point(inst.Transform:GetWorldPosition())
      if pt.y <= .1 then
         pt.y = 0
         inst.Physics:Stop()
         inst.Physics:Teleport(pt.x,pt.y,pt.z)
		 inst.mobteleported = true
      end
	end
end

------------------------------------------------------

local function StartTimer(inst, duration)
    inst.charge_time = duration
	inst.specialatk = false

    if inst.charge_task == nil then
        inst.charge_task = inst:DoPeriodicTask(1, onupdate, nil, 1)
        onupdate(inst, 0)
    end
end

local function SetAdult(inst)
	if not inst:HasTag("playerghost") then
    inst.AnimState:SetBank("tallbird")
	if inst.isshiny ~= 0 then
	inst.AnimState:SetBuild("tallbird_shiny_build_0"..inst.isshiny)
	else
    inst.AnimState:SetBuild("ds_tallbird_basic")
	end
    inst:SetStateGraph("SGtallbirdplayer")
	end
	inst.components.lootdropper:SetLoot({"meat", "meat"})
	inst:AddTag("tallbird")
	inst:RemoveTag("smallbird")
	inst:RemoveTag("teenbird")
	inst:AddTag("mommy")
	inst:AddTag("special_atk2")
	inst.Transform:SetScale(1.0, 1.0, 1.0)
	--inst:AddComponent("healthRegenerate")
	if MONSTERHUNGER == "Disable" then
		inst.components.hunger:Pause()
	end
	inst.components.combat.playerdamagepercent = MOBPVP
    --inst.components.combat:SetAttackPeriod(3)
	inst.components.combat:SetRange(TUNING.TALLBIRD_ATTACK_RANGE)
	inst.components.eater:SetDiet({ FOODGROUP.OMNI }, { FOODGROUP.OMNI })
	inst.components.eater:SetAbsorptionModifiers(3,2,2)
	inst.components.locomotor.walkspeed = (7)
    inst.components.locomotor.runspeed = (7)
	inst.components.combat:SetDefaultDamage(35*2)
	inst.AnimState:PlayAnimation("idle")
	--inst.sg:GoToState("taunt")
	inst.AnimState:Hide("beakfull")
	
	inst.Transform:SetScale(1.0, 1.0, 1.0)
	
	inst.components.temperature.maxtemp = 60
	inst.components.temperature.mintemp = 20
	
	MakeCharacterPhysics(inst, 10, 1.33)
    inst.DynamicShadow:SetSize( 6, 3 )
    inst.DynamicShadow:Enable(false)
	MakeLargeBurnableCharacter(inst, "head")
end

local function SetTeen(inst)

	if not inst:HasTag("playerghost") then --just added incase of weirdness.
    inst.AnimState:SetBank("tallbird")
	if inst.isshiny ~= 0 then
	inst.AnimState:SetBuild("teenbird_shiny_build_0"..inst.isshiny)
	else
    inst.AnimState:SetBuild("tallbird_teen_build")
	end
    inst:SetStateGraph("SGteenbirdp")
	end
	if MONSTERHUNGER == "Disable" then
		inst.components.hunger:Pause()
	end
	inst.components.combat.playerdamagepercent = MOBPVP
    inst.components.combat:SetAttackPeriod(1.5)
	inst.components.combat:SetRange(2)
	inst.components.locomotor.walkspeed = (8)
    inst.components.locomotor.runspeed = (8)
	inst.components.combat:SetDefaultDamage(20*2)
	inst.components.lootdropper:SetLoot({"meat"})
	inst.components.eater:SetDiet({ FOODGROUP.OMNI }, { FOODGROUP.OMNI })
	inst.components.eater:SetAbsorptionModifiers(3,2,2)
	inst:AddTag("teenbird")
	inst:RemoveTag("smallbird")
	inst.AnimState:PlayAnimation("idle")
	--inst.components.eater.caneat = food2prefs
	--inst.components.eater.preferseating = food2prefs
	--inst.sg:GoToState("taunt")
	inst.AnimState:Hide("beakfull")
	inst.Transform:SetScale(0.8, 0.8, 0.8)
	MakeCharacterPhysics(inst, 10, 0.25)
    inst.DynamicShadow:SetSize(2.75, 1)
	
	inst.components.temperature.maxtemp = 60
	inst.components.temperature.mintemp = 20
	inst.components.moisture:SetInherentWaterproofness(1)
	MakeLargeBurnableCharacter(inst, "head")
end

local function OnAdult(inst)
	inst.Transform:SetPosition(inst.Transform:GetWorldPosition())
	inst.sg:GoToState("growup2")
	
    --inst:SetStateGraph("SGtallbirdplayer")
	--SetAdult(inst)
	--applyupgrades(inst)

end

local function OnTeen(inst)
	inst.Transform:SetPosition(inst.Transform:GetWorldPosition())
	--inst.AnimState:SetBank("tallbird")
    --inst.AnimState:SetBuild("tallbird_teen_build")
    --inst:SetStateGraph("SGteenbirdp")
	inst.sg:GoToState("growup")
	--SetTeen(inst)
	--applyupgrades(inst)
	

end

local function applyupgrades(inst)

    local health_percent = inst.components.health:GetPercent()
	local hunger_percent = inst.components.hunger:GetPercent()
	--local sanity_percent = inst.components.sanity:GetPercent()
	
	if inst.birdfood == 0 and inst.birdfood < 30 then
	inst.components.health.maxhealth = 100
	inst.components.hunger.max = 50
	
	end
	
    if inst.birdfood >= 30 and inst.birdfood < 90 then
    inst.components.health.maxhealth = 200
	inst.components.hunger.max = 100
	
	inst.components.health:SetPercent(health_percent)
	
	
    end
	
	if inst.birdfood >= 90 then
    inst.components.health.maxhealth = 300
	inst.components.hunger.max = 175
	
	inst.components.health:SetPercent(health_percent)
	OnAdult(inst)
	
    end

    inst.components.health:SetPercent(health_percent)
end

local function EquipHat(inst)
    local head = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD)
	if head then

	inst.AnimState:Show("HEAD")
        
		
	end 
	
end

local function OnEat(inst, food)
    if food and food.components.edible then
		if food.components.edible.foodtype == FOODTYPE.MEAT or food.components.edible.foodtype == FOODTYPE.VEGGIE or food.components.edible.foodtype == FOODTYPE.SEEDS and MOB_TALLBIRD == "Enable" then
			--food helps you grow!
			if inst.birdfood < 999 then
			inst.birdfood = inst.birdfood + 1
			end
			if inst.birdfood >= 30 and inst.birdfood < 90 and inst:HasTag("smallbird") then
				--inst.sg:GoToState("transform")
				OnTeen(inst)
				applyupgrades(inst)
			end
		
			if inst.birdfood >= 90 and not inst:HasTag("mommy") then
				--inst.sg:GoToState("transform2")
				OnAdult(inst)
				applyupgrades(inst)
			end
		end
    end
end

local function ondeath(inst)
        inst.birdfood = 0
        applyupgrades(inst)
end


local function RestoreNightvision(inst)

	inst:DoTaskInTime(3, function(inst) 
	inst.Light:Enable(true)
	inst.Light:SetRadius(0)
	inst.Light:SetFalloff(.5)
	inst.Light:SetIntensity(.6)
	inst.Light:SetColour(245/255,40/255,0/255)
	end, inst)
end


local function OnPreload(inst, data)
    if data ~= nil and data.birdfood ~= nil then
        inst.birdfood = data.birdfood
        applyupgrades(inst)
        --re-set these from the save data, because of load-order clipping issues
        if data.health and data.health.health then inst.components.health:SetCurrentHealth(data.health.health) end
        if data.hunger and data.hunger.hunger then inst.components.hunger.current = data.hunger.hunger end
        --if data.sanity and data.sanity.current then inst.components.sanity.current = data.sanity.current end
        inst.components.health:DoDelta(0)
        inst.components.hunger:DoDelta(0)
        --inst.components.sanity:DoDelta(0)
    end
end

local function RemovePenalty(inst)
	inst.components.health:DeltaPenalty(-1.00) --Removes health penalty when reviving
	--inst.components.health:DoDelta(20000, false) --Returns heals to max health upon reviving
end

local function OnLoad(inst, data)
	if data ~= nil then
		inst.birdfood = data.birdfood or 0	
		inst.mobteleported = data.mobteleported or false
		inst.isshiny = data.isshiny or 0
		if data.charge_time ~= nil then
		StartTimer(inst, data.charge_time)
		end
	end
end

local function OnSave(inst, data)
	data.birdfood = inst.birdfood > 0 and inst.birdfood or nil
	 data.charge_time = inst.charge_time > 0 and inst.charge_time or nil
	 data.mobteleported = inst.mobteleported or false
	 data.isshiny = inst.isshiny or 0
end

local function setSkin(inst)
	if not inst:HasTag("playerghost") then
		local mobskin = inst.components.skinner.skin_name
		local getshiny = (mobskin ~= inst.prefab and mobskin ~= "") and string.gsub(mobskin, inst.prefab.."_", "" ) --will return false if no skin is equipped.
		if SKIN_RARITY_COLORS.ModMade ~= nil then
			if getshiny ~= false then
				inst.isshiny = getshiny --used for other purposes
				if inst.birdfood < 30  then
				inst.AnimState:SetBuild("smallbird_shiny_build_0"..inst.isshiny)
				elseif inst.birdfood >= 30 and inst.birdfood < 90 then
				inst.AnimState:SetBuild("teenbird_shiny_build_0"..inst.isshiny)
				else
				inst.AnimState:SetBuild("tallbird_shiny_build_0"..inst.isshiny)
				end
			end		
		end
	end	
end

local function GetPeepChance(inst)
    local peep_percent = 0.1
    if inst.components.hunger then
        if inst.components.hunger:IsStarving() then
            peep_percent = 1
        elseif inst.components.hunger:GetPercent() < .25 then
            peep_percent = 0.9
        elseif inst.components.hunger:GetPercent() < .5 then
            peep_percent = 0.75
        end
    end
    --print("smallbird - GetPeepChance", peep_percent)
    return peep_percent
end

local function setChar(inst)
	if inst.birdfood < 30 then
	if not inst:HasTag("playerghost") then
    inst.AnimState:SetBank("smallbird")
	if inst.isshiny ~= 0 then
	inst.AnimState:SetBuild("smallbird_shiny_build_0"..inst.isshiny)
	else
    inst.AnimState:SetBuild("smallbird_basic")
	end
    inst:SetStateGraph("SGsmallbirdp")
	end
	inst.components.sanity.ignore = true
	end
	if inst.birdfood >= 30 and inst.birdfood < 90 then
	SetTeen(inst)
	--inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	end
	if inst.birdfood >= 90 then
	SetAdult(inst)
	--inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	end
	
	if MOBPVPMODE == "Enable" then
		PvPTeleport(inst)
	end
end

local NIGHTVISION_COLOURCUBES =
{
    day = "images/colour_cubes/insane_day_cc.tex",
    dusk = "images/colour_cubes/insane_dusk_cc.tex",
    night = "images/colour_cubes/purple_moon_cc.tex",
    full_moon = "images/colour_cubes/purple_moon_cc.tex",
}

local function SetNightVision(inst, enable)
    if TheWorld.state.isnight or TheWorld:HasTag("cave") then
        inst.components.playervision:ForceNightVision(true)
        inst.components.playervision:SetCustomCCTable(NIGHTVISION_COLOURCUBES)
    else
        inst.components.playervision:ForceNightVision(false)
        inst.components.playervision:SetCustomCCTable(nil)
    end
end

local common_postinit = function(inst) 
	inst.soundsname = "wilson"

	inst.MiniMapEntity:SetIcon( "smallbirdp.tex" )
	
	inst.AnimState:PlayAnimation("idle")
	
	inst:DoTaskInTime(0, function()
   if ThePlayer then
      inst:EnableMovementPrediction(false)
   end
end)

	inst:WatchWorldState( "isday", function() SetNightVision(inst) end)
  	inst:WatchWorldState( "isdusk", function() SetNightVision(inst) end)
  	inst:WatchWorldState( "isnight", function() SetNightVision(inst)  end)
	
	SetNightVision(inst, true)
end

local function DontTriggerCreep(inst)
	inst.components.locomotor.walkspeed = (6)
    inst.components.locomotor.runspeed = (6)
	--inst.components.locomotor:SetSlowMultiplier( 1 )
    --inst.components.locomotor:SetTriggersCreep(false)
    --inst.components.locomotor.pathcaps = { ignorecreep = true }
end


local master_postinit = function(inst)
	
    inst.components.health:SetMaxHealth(100)
	inst.components.hunger:SetMax(50)
	inst.components.hunger:SetRate(0.15)
	--inst:AddComponent("healthRegenerate")
	inst.components.combat.playerdamagepercent = MOBPVP
    --inst.components.combat:SetAttackPeriod(2)
	inst.components.combat:SetRange(1.5)
	inst.components.locomotor.walkspeed = (6)
    inst.components.locomotor.runspeed = (6)
	inst.components.locomotor.fasteronroad = false
	inst.components.combat:SetDefaultDamage(5*2)
	--inst.components.combat:SetHurtSound("dontstarve/creatures/hound/hit")
	--inst.components.temperature.hurtrate = 0
    inst.components.temperature.inherentinsulation = -TUNING.INSULATION_SMALL
	--inst.AnimState:SetBank("sharkitten")
	--inst.AnimState:SetBuild("sharkitten_build")	
	inst.OnSetSkin = function(skin_name)
    --inst.AnimState:SetBuild("sharkitten_build")
	--inst:SetStateGraph("SGsharkittenp")
	
	inst:ListenForEvent("ms_respawnedfromghost", DontTriggerCreep)
    DontTriggerCreep(inst)

	
	end
	--inst:SetStateGraph("SGsharkittenp")
	
	--inst:AddComponent("locomotor")
    --inst.components.locomotor:SetSlowMultiplier( 1 )
    --inst.components.locomotor:SetTriggersCreep(false)
    --inst.components.locomotor.pathcaps = { ignorecreep = true }
	
	inst.birdfood = 0
	inst.charge_task = nil
    inst.charge_time = 0
	inst.specialatk = true
	
	inst.components.locomotor:SetShouldRun(true)
	inst.components.talker:IgnoreAll()
	if MONSTERHUNGER == "Disable" or inst:HasTag("mommy") then
		inst.components.hunger:Pause()
	end
	inst.components.sanity.ignore = true
	--inst.HUD.controls.status.stomach:Hide()
	
	--inst:ListenForEvent("onhitother", OnHitOther)
	MakeSmallBurnableCharacter(inst, "head")
	
	
	inst:AddComponent("lootdropper")
    inst.components.lootdropper:SetChanceLootTable('smallbirdp')
	--inst.components.health.fire_damage_scale = 0 -- Take no damage from fire 
	inst.components.eater:SetOnEatFn(OnEat)
	
	--inst.components.eater:SetDiet({ FOODTYPE.VEGGIE }, { FOODTYPE.VEGGIE })
	inst.components.eater.caneat = foodprefs
	inst.components.eater.preferseating = foodprefs
	inst.components.eater:SetAbsorptionModifiers(4,3,3)
	-- local inst.num_good_food_eaten = 0
	 
	--inst:AddTag("prey")
	inst:AddTag("smallbird")
	inst:AddTag("mobplayer")
	inst:AddTag("mobsleep")
	inst:AddTag("special_atk1")
    
	
	inst.userfunctions =
    {
        GetPeepChance = GetPeepChance,
        SetTeen = SetTeen,
        SetAdult = SetAdult,
		StartTimer = StartTimer,
    }
	
	inst.birdfood = 0
	inst.isshiny = 0
	
	inst.ghostbuild = "ghost_monster_build"
	inst.mobteleported = false
	
	--inst:ListenForEvent("attacked", OnAttacked)

	MakeCharacterPhysics(inst, 10, 0.25)
    --inst.DynamicShadow:SetSize( 2.5, 1.5 )
    --inst.DynamicShadow:Enable(false)
    inst.Transform:SetFourFaced()
	
	inst.OnLongUpdate = OnLongUpdate
	inst.OnSave = OnSave
	inst.OnLoad = OnLoad
	inst.OnPreLoad = OnPreload
	
	--inst.components.temperature.maxtemp = 60
	--inst.components.temperature.mintemp = 20
	--inst.components.moisture:SetInherentWaterproofness(1)
	
	inst:ListenForEvent("death", ondeath)
	inst:ListenForEvent("equip", EquipHat)
	--inst:ListenForEvent("equip", SetWeaponDamage)
	--inst:ListenForEvent("unequip", UnEquip)
    
	
	------------------
    
    ------------------

	
  	local light = inst.entity:AddLight() --Can't see at night but is immune to Grue
  	inst.Light:Enable(true)
  	inst.Light:SetRadius(0)
  	inst.Light:SetFalloff(0.6)
  	inst.Light:SetIntensity(0.6)
  	inst.Light:SetColour(180/255,195/255,255/255)
	
	--No nightvision, makes a need for lightsources during the night to work.
  	--inst:WatchWorldState( "isday", function() SetNightVision(inst) end)
  	--inst:WatchWorldState( "isdusk", function() SetNightVision(inst) end)
  	--inst:WatchWorldState( "isnight", function() SetNightVision(inst)  end)
	
	--SetNightVision(inst, true)
	
	inst.components.talker.colour = Vector3(127/255, 0/255, 0/255)
	inst:ListenForEvent("respawnfromghost", RestoreNightvision)
	
	

    inst:DoTaskInTime(0, setChar)
	inst:DoTaskInTime(3, setSkin)
	
    inst:ListenForEvent("respawnfromghost", function()
		inst:DoTaskInTime(3, function()  inst.components.health:SetInvincible(false)
            if inst.components.playercontroller ~= nil then
				inst.components.playercontroller:EnableMapControls(true)
				inst.components.playercontroller:Enable(true)
			end
			inst.components.inventory:Show()
			inst:ShowActions(true)
            inst:ShowHUD(true)
            inst:SetCameraDistance()
			inst.sg:RemoveStateTag("busy")
            SerializeUserSession(inst) 
		end)
        inst:DoTaskInTime(5, setChar)
		inst:DoTaskInTime(5.1, setSkin)
		inst:DoTaskInTime(6, DontTriggerCreep)
		inst:DoTaskInTime(6, RemovePenalty)
		inst:DoTaskInTime(10, RestoreNightvision)
    end)
	
	
    return inst
	
end

if SKIN_RARITY_COLORS.ModMade ~= nil then
AddModCharacterSkin("smallbirdp", 1, {normal_skin = "deerclops_shiny_build_01", ghost_skin = "ghost_monster_build"}, {"deerclops_shiny_build_01", "ghost_monster_build"}, {"DEERPLAYER", "FORMAL"})
end

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