require("stategraphs/commonstates")

local function SpecialTimer(inst)
inst:RemoveTag("nospecial")
end

function TableConcat(t1,t2)
    for i=1,#t2 do
        t1[#t1+1] = t2[i]
    end
    return t1
end

local actionhandlers = 
{
	ActionHandler(ACTIONS.ATTACK, "attack"),
	ActionHandler(ACTIONS.PICKUP, "eat"),
	ActionHandler(ACTIONS.DROP, "eat"),
	ActionHandler(ACTIONS.EAT, "eat"),
	ActionHandler(ACTIONS.HARVEST, "peck"),
	ActionHandler(ACTIONS.PICK, "peck"),
	ActionHandler(ACTIONS.FEED, "peck"),
	ActionHandler(ACTIONS.GIVE, "peck"),
	ActionHandler(ACTIONS.GIVETOPLAYER, "peck"),
	ActionHandler(ACTIONS.GIVEALLTOPLAYER, "peck"),
	ActionHandler(ACTIONS.MIGRATE, "peck"),
	ActionHandler(ACTIONS.COMBINESTACK, "attack"),
	ActionHandler(ACTIONS.UNWRAP, "peck"),	
}

local mobCraftActions =
{
	ActionHandler(ACTIONS.GOHOME, "gohome"),
	ActionHandler(ACTIONS.ATTACK, "attack"),
	ActionHandler(ACTIONS.FEED, "attack"),
	ActionHandler(ACTIONS.PICKUP, "eat"),
	ActionHandler(ACTIONS.DROP, "eat"),
	ActionHandler(ACTIONS.ACTIVATE, "special_atk1"),
	ActionHandler(ACTIONS.SLEEPIN, "sleep"),
	ActionHandler(ACTIONS.EAT, "eat"),
	ActionHandler(ACTIONS.HEAL, "attack"),
	ActionHandler(ACTIONS.FAN, "attack"),
	ActionHandler(ACTIONS.DIG, "attack"),
	ActionHandler(ACTIONS.CHOP, "attack"),
	ActionHandler(ACTIONS.MINE, "attack"),
	ActionHandler(ACTIONS.COOK, "attack"),
	ActionHandler(ACTIONS.FILL, "attack"),
	ActionHandler(ACTIONS.DRY, "attack"),
	ActionHandler(ACTIONS.ADDFUEL, "attack"),
	ActionHandler(ACTIONS.ADDWETFUEL, "attack"),
	ActionHandler(ACTIONS.LIGHT, "attack"),
	ActionHandler(ACTIONS.BAIT, "attack"),
	ActionHandler(ACTIONS.BUILD, "attack"),
	ActionHandler(ACTIONS.PLANT, "attack"),
	ActionHandler(ACTIONS.REPAIR, "attack"),
	ActionHandler(ACTIONS.HARVEST, "attack"),
	ActionHandler(ACTIONS.STORE, "attack"),
	ActionHandler(ACTIONS.RUMMAGE, "attack"),
	ActionHandler(ACTIONS.DEPLOY, "attack"),
	ActionHandler(ACTIONS.HAMMER, "attack"),
	ActionHandler(ACTIONS.FERTILIZE, "attack"),
	ActionHandler(ACTIONS.MURDER, "attack"),
	ActionHandler(ACTIONS.UNLOCK, "attack"),
	ActionHandler(ACTIONS.TURNOFF, "attack"),
	ActionHandler(ACTIONS.TURNON, "attack"),
	ActionHandler(ACTIONS.SEW, "attack"),
	ActionHandler(ACTIONS.COMBINESTACK, "attack"),
	ActionHandler(ACTIONS.UPGRADE, "attack"),
	ActionHandler(ACTIONS.WRITE, "attack"),
	ActionHandler(ACTIONS.FEEDPLAYER, "attack"),
	ActionHandler(ACTIONS.TERRAFORM, "attack"),
	ActionHandler(ACTIONS.NET, "attack"),
	ActionHandler(ACTIONS.CHECKTRAP, "attack"),
	ActionHandler(ACTIONS.SHAVE, "attack"),
	ActionHandler(ACTIONS.FISH, "attack"),
	ActionHandler(ACTIONS.REEL, "attack"),
	ActionHandler(ACTIONS.CATCH, "attack"),
	ActionHandler(ACTIONS.TEACH, "attack"),
	ActionHandler(ACTIONS.MANUALEXTINGUISH, "attack"),
	ActionHandler(ACTIONS.RESETMINE, "attack"),
	ActionHandler(ACTIONS.BLINK, "attack"),
	ActionHandler(ACTIONS.GIVE, "attack"),
	ActionHandler(ACTIONS.GIVEALLTOPLAYER, "attack"),
	--ActionHandler(ACTIONS.CHANGEIN, "changeskin"),
	ActionHandler(ACTIONS.SMOTHER, "attack"),
	ActionHandler(ACTIONS.CASTSPELL, "attack"),
	ActionHandler(ACTIONS.WRAPBUNDLE, "attack"),
	ActionHandler(ACTIONS.UNWRAP, "attack"),
	ActionHandler(ACTIONS.UNLOCK, "attack"),
	ActionHandler(ACTIONS.USEKLAUSSACKKEY, "attack"),
}

local extraActions = 
{
	--ActionHandler(ACTIONS.SLEEPIN, "sleep"),
	ActionHandler(ACTIONS.TRAVEL, "taunt"),
	ActionHandler(ACTIONS.LOOKAT, "taunt"),
}

if MOBCRAFT == "Enable" then
	extraActions = mobCraftActions
end

actionhandlers = TableConcat(actionhandlers, extraActions)

local events=
{
    EventHandler("attacked", function(inst) if not inst.components.health:IsDead() and not inst.sg:HasStateTag("attack") and not inst.sg:HasStateTag("busy") then inst.sg:GoToState("hit") end end),
    EventHandler("death", function(inst) inst.sg:GoToState("death") end),
    EventHandler("doattack", function(inst, data) if not inst.components.health:IsDead() and (inst.sg:HasStateTag("hit") or not inst.sg:HasStateTag("busy")) then inst.sg:GoToState("attack", data.target) end end),
    CommonHandlers.OnSleep(),
    CommonHandlers.OnLocomote(true,false),
    CommonHandlers.OnFreeze(),
	
	 EventHandler("ms_opengift",
        function(inst)
            if not inst.sg:HasStateTag("busy") then
                inst.sg:GoToState("opengift")
            end
        end),
}


 local states=
{
	
	State{
        name = "idle",
        tags = {"idle", "canrotate"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            
          
            inst.AnimState:PlayAnimation("idle", true)
    

            if inst:HasTag("teenbird") then
                inst.sg:SetTimeout(4 + 4*math.random())
            end
        end,
        
        ontimeout = function(inst)
            --print("tallbird - idle timeout")
            if inst:HasTag("teenbird") then
                if math.random() <= inst.userfunctions.GetPeepChance(inst) then
                    inst.sg:GoToState("idle_peep")
                else
                    inst.sg:GoToState("idle_blink")
                end
            end
        end,
    },
    
    State{
        name = "idle_blink",
        tags = {"idle"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("idle_blink", true)
        end,
       
        timeline = 
        {
            TimeEvent(26*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/teenbird/blink") end),
        },

        events=
        {
            EventHandler("animover", 
                function(inst,data) 
                    if math.random() < 0.1 then
                        inst.sg:GoToState("idle_blink")
                    else
                        inst.sg:GoToState("idle")
                    end
                end
            ),
        },
    },

    State{
        name = "idle_peep",
        tags = {"idle"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("hungry", true)
        end,
       
        timeline = 
        {
            TimeEvent(8*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/teenbird/chirp") end),
            TimeEvent(25*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/teenbird/chirp") end),
        },

        events=
        {
            EventHandler("animover", 
                function(inst,data) 
                    if math.random() <= inst.userfunctions.GetPeepChance(inst) then
                        inst.sg:GoToState("idle_peep")
                    else
                        inst.sg:GoToState("idle")
                    end
                end
            ),
        },
    },

    State{
        name = "idle_taunt",
        tags = {"idle"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("taunt")
            inst.SoundEmitter:PlaySound("dontstarve/creatures/teenbird/chirp")
        end,
       
        timeline=
        {
            TimeEvent(6*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/teenbird/scratch_ground") end),
            TimeEvent(30*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/teenbird/scratch_ground") end),
        },

        events=
        {
            EventHandler("animover", 
                function(inst,data) 
                    inst.sg:GoToState("idle")
                end
            ),
        },
    },

    State{
        name = "lay",
        tags = {"busy"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("layegg")
        end,
		
		
        
        timeline=
        {
            TimeEvent(25*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/egg") end),
            TimeEvent(65*FRAMES, function(inst) inst:PerformBufferedAction() end),
        },
        
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
        },
        
    },
    
	State{
        name = "special_atk2",
        tags = {"busy"},
        
        onenter = function(inst)
            if inst:HasTag("nospecial") then
				inst.sg:GoToState("idle")
			else
				inst.sg:GoToState("lay2")
			end	
        end,
		
		onexit = function(inst)
            
        end,
        
        timeline=
        {
           
        },
        
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") 
			--inst:AddTag("nospecial") 
			end),
        },
        
    },
	
	State{
        name = "lay2",
        tags = {"busy"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("layegg")
			inst:AddTag("nospecial")
        end,
		
		onexit = function(inst)
            
        end,
        
        timeline=
        {
            TimeEvent(25*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/egg") end),
            TimeEvent(65*FRAMES, function(inst)
					local egg = SpawnPrefab("tallbirdegg")
					local pt = inst:GetPosition()
					egg.Transform:SetPosition(pt:Get())
				end),
        },
        
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") inst:DoTaskInTime(8640, function() inst:RemoveTag("nospecial")
			end) end),
        },
        
    },

    State{
        name = "taunt",
        tags = {"busy", "canrotate"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("taunt")
            inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/chirp")
            if inst.components.combat and inst.components.combat.target then
                inst:FacePoint(Vector3(inst.components.combat.target.Transform:GetWorldPosition()))
            end
        end,
        
        timeline=
        {
            TimeEvent(6*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/scratch_ground") end),
            TimeEvent(30*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/scratch_ground") end),
        },
        
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
        },
    },    
	
	State{
        name = "special_atk1",
        tags = {"busy", "canrotate"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("taunt")
            inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/chirp")
        end,
        
        timeline=
        {
            TimeEvent(6*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/scratch_ground") end),
            TimeEvent(30*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/scratch_ground") end),
        },
        
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
        },
    },    
    
    State{
        name = "attack",
        tags = {"attack", "busy"},
        
        onenter = function(inst, cb)
            inst.Physics:Stop()
            inst.components.combat:StartAttack()
            inst.AnimState:PlayAnimation("atk_pre")
            inst.AnimState:PushAnimation("atk", false)
        end,
        
        timeline=
        {
            TimeEvent(10*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/attack") end),
            TimeEvent(12*FRAMES, function(inst) inst:PerformBufferedAction() end),
            TimeEvent(14*FRAMES, function(inst) 
				inst.sg:RemoveStateTag("attack")
				inst.sg:RemoveStateTag("busy")
			end),
        },
        
        events=
        {
            EventHandler("animqueueover", function(inst) inst.sg:GoToState("idle") end),
        },
    },

    State{
        name = "peck",
        tags = {"attack", "canrotate"},
        
        onenter = function(inst, cb)
            inst.Physics:Stop()
            inst.components.combat:StartAttack()
            inst.AnimState:PlayAnimation("teenatk_pre")
            inst.AnimState:PushAnimation("teenatk", false)
        end,
        
        timeline =
        {
            TimeEvent(11*FRAMES, function(inst)
                inst.SoundEmitter:PlaySound("dontstarve/creatures/teenbird/peck")
            end),
            TimeEvent(13*FRAMES, function(inst)
                inst:PerformBufferedAction()
                local target = inst.components.combat.target
                if target and target.components.talker then
                    target.components.talker:Say( GetString(target, "ANNOUNCE_PECKED") )
                end
            end),
        },
        
        events =
        {
            EventHandler("animqueueover", function(inst) inst.sg:GoToState("idle") end),
        },
    },

    
    State{
        name = "hit",
        tags = {"hit"},
        
        onenter = function(inst)
            inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/hurt")
            inst.AnimState:PlayAnimation("hit")
            inst.Physics:Stop()            
        end,
        
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end ),
        },        
    },    

    
    State{
        name = "gohome",
        tags = {"busy"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            if inst.components.sleeper then
                inst.components.sleeper:GoToSleep()
            end
        end,
        
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end ),
        },
    },    
    
    State{
        name = "eat",
        tags = {"busy"},
        
        onenter = function(inst)
            inst.Physics:Stop()            
            inst.AnimState:PlayAnimation("steal")
            inst.SoundEmitter:PlaySound("dontstarve/creatures/smallbird/scratch_ground")
        end,
        
        timeline=
        {
            TimeEvent(11*FRAMES, function(inst) inst:PerformBufferedAction() end),
        },
        
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end ),
        },        
    },

    State{
        name = "growup2",
        tags = {"busy"},
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("growadult")
        end,
        timeline = 
        {
            TimeEvent(43*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/teenbird/grow") end),
            TimeEvent(45*FRAMES, function(inst) inst.Transform:SetScale(1,1,1)  end),
        },
        events=
        {
            EventHandler("animover", function(inst)
                inst.userfunctions.SetAdult(inst)
            end),
        },
    },
	
	State{
        name = "opengift",
        tags = { "busy", "pausepredict" },

        onenter = function(inst)
            inst.components.locomotor:Stop()
            inst.components.locomotor:Clear()
            inst:ClearBufferedAction()

            --if IsNearDanger(inst) then
                --inst.sg.statemem.isdanger = true
                --inst.sg:GoToState("idle")
                --if inst.components.talker ~= nil then
                   -- inst.components.talker:Say(GetString(inst, "ANNOUNCE_NODANGERGIFT"))
                --end
                --return
           -- end

            inst.SoundEmitter:PlaySound("dontstarve/common/player_receives_gift")
            inst.AnimState:PlayAnimation("idle")
            --inst.AnimState:PushAnimation("idle", true)
            -- NOTE: the previously used ripping paper anim is called "giift_loop"

            if inst.components.playercontroller ~= nil then
                inst.components.playercontroller:RemotePausePrediction()
                inst.components.playercontroller:EnableMapControls(false)
                inst.components.playercontroller:Enable(false)
            end
            inst.components.inventory:Hide()
            inst:PushEvent("ms_closepopups")
            inst:ShowActions(false)
            inst:ShowGiftItemPopUp(true)

            if inst.components.giftreceiver ~= nil then
                inst.components.giftreceiver:OnStartOpenGift()
            end
        end,

        timeline =
        {
            -- Timing of the gift box opening animation on giftitempopup.lua
            TimeEvent(155 * FRAMES, function(inst)
               -- inst.AnimState:PlayAnimation("gift_open_pre")
                --inst.AnimState:PushAnimation("idle", true)
            end),
        },

        events =
        {
            EventHandler("firedamage", function(inst)
                inst.AnimState:PlayAnimation("idle", true)
                inst.sg:GoToState("idle", true)
                if inst.components.talker ~= nil then
                    inst.components.talker:Say(GetString(inst, "ANNOUNCE_NODANGERGIFT"))
                end
            end),
            EventHandler("ms_doneopengift", function(inst, data)
                inst.sg:GoToState("idle", true)
            end),
        },

        onexit = function(inst)
            if inst.sg.statemem.isdanger then
                return
            elseif not inst.sg.statemem.isopeningwardrobe then
                if inst.components.playercontroller ~= nil then
                    inst.components.playercontroller:EnableMapControls(true)
                    inst.components.playercontroller:Enable(true)
                end
                inst.components.inventory:Show()
                inst:ShowActions(true)
            end
            inst:ShowGiftItemPopUp(false)
        end,
    },

	State {
        name = "sleep",
        tags = { "sleeping" }, --add tag "busy" if you hate sliding

        onenter = function(inst)
            if inst.components.locomotor ~= nil then
                inst.components.locomotor:StopMoving()
            end
            inst.AnimState:PlayAnimation("sleep_pre")
            --if fns ~= nil and fns.onsleep ~= nil then
                --fns.onsleep(inst)
            --end
        end,

        --timeline = timelines ~= nil and timelines.starttimeline or nil,
		
		timeline = 
	{
		TimeEvent(0*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/sleep") end ),
	},

        events =
        {
            EventHandler("animqueueover", function(inst) inst.sg:GoToState("sleeping") end ),
            EventHandler("onwakeup", function(inst) inst.sg:GoToState("wake") end),
        },
    },

    State
    {
        name = "sleeping",
        tags = { "sleeping" },

        --onenter = onentersleeping,
		
		onenter = function(inst)
				inst.components.locomotor:StopMoving()
				local hungerpercent = inst.components.hunger:GetPercent()
				if hungerpercent ~= nil and hungerpercent ~= 0 then -- We don't want players to heal out starvation.
				inst.components.health:DoDelta(0.1, false)
				end
				--inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/sleep")
				inst.AnimState:PlayAnimation("sleep_loop")
			end,

        --timeline = timelines ~= nil and timelines.sleeptimeline or nil,
		timeline=
        {
			--TimeEvent(0*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/vargr/sleep") end)
        },

        events =
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("sleeping") end ),
			EventHandler("onwakeup", function(inst) inst.sg:GoToState("wake") end),
        },
    },

    State
    {
        name = "wake",
        tags = { "busy", "waking" },

        onenter = function(inst)
            if inst.components.locomotor ~= nil then
                inst.components.locomotor:StopMoving()
            end
            inst.AnimState:PlayAnimation("sleep_pst")
            if inst.components.sleeper ~= nil and inst.components.sleeper:IsAsleep() then
                inst.components.sleeper:WakeUp()
            end
            --if fns ~= nil and fns.onwake ~= nil then
                --fns.onwake(inst)
            --end
        end,

        timeline = 
		{
			TimeEvent(0*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/wakeup") end ),
		},

        events =
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
        },
    },
	
	

    State{
        name = "death",
        tags = {"busy"},

        onenter = function(inst)
            inst.AnimState:PlayAnimation("death")
			
            inst.Physics:Stop()
            RemovePhysicsColliders(inst)
            inst.components.lootdropper:DropLoot(inst:GetPosition())
			inst.components.inventory:DropEverything(true)
			inst.birdfood = 0
			
            if inst.components.playercontroller ~= nil then
                inst.components.playercontroller:RemotePausePrediction()
            end
        end,
		
		timeline=
		{
			TimeEvent(0*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/death") end)
		},
		
        events =
        {
            EventHandler("animover", function(inst)
                if inst.AnimState:AnimDone() then
                    if MOBGHOST == "Enable" then
                     inst:PushEvent(inst.ghostenabled and "makeplayerghost" or "playerdied", { skeleton = false })
					else
						TheWorld:PushEvent("ms_playerdespawnanddelete", inst)
					end
                end
            end),
        },
    },
	
	State
    {
        name = "run_start",
        tags = { "moving", "running", "canrotate" },

        onenter = function(inst)
			inst.components.locomotor:WalkForward()
            inst.AnimState:PlayAnimation("walk_pre")
			
        end,

        events =
        {
            EventHandler("animqueueover", function(inst) inst.sg:GoToState("run") end ),
        },
    },
	
	State
    {
        name = "run",
        tags = { "moving", "running", "canrotate" },

        onenter = function(inst)
			inst.components.locomotor:WalkForward()
			inst.AnimState:PlayAnimation("walk_loop")
        end,
		
		timeline =
        {
            TimeEvent(0*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/footstep") end ),
		TimeEvent(12*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/tallbird/footstep") end ),
        },
		
        events=
			{
				EventHandler("animqueueover", function(inst) inst.sg:GoToState("run") end ),
			},

    },
	
	State
    {
        name = "run_stop",
        tags = { "idle" },

        onenter = function(inst) 
            inst.components.locomotor:StopMoving()
			inst.AnimState:PlayAnimation("walk_pst")
			
            
        end,


        events =
        {
            EventHandler("animqueueover", function(inst) inst.sg:GoToState("idle") end ),
        },
    },
	
}

  

CommonStates.AddFrozenStates(states)
    



    
return StateGraph("teenbirdp", states, events, "idle", actionhandlers)

