require("stategraphs/commonstates")

local SHAKE_DIST = 40

local function onattackfn(inst)
	if inst.components.health and not inst.components.health:IsDead()
		and (inst.sg:HasStateTag("hit") or not inst.sg:HasStateTag("busy")) then
		-- Clear out the inventory if he got interrupted
		local target = inst.components.inventory:FindItem(function(item) return inst.components.eater:CanEat(item) end)
		while target do
			target:Remove()
			target = inst.components.inventory:FindItem(function(item) return inst.components.eater:CanEat(item) end)
		end

		if inst.components.combat and inst.components.combat.target and inst.components.combat.target:HasTag("beehive") then
			inst.sg:GoToState("attack")
			return
		end

		if not inst.cangroundpound and not inst.components.timer:TimerExists("GroundPound") then
			inst.components.timer:StartTimer("GroundPound", 10)
		end

		if inst.sg:HasStateTag("running") then
			inst.sg:GoToState("pound")
		else
			if inst.cangroundpound then
				inst.sg:GoToState("pound")
			else
				inst.sg:GoToState("attack")
			end
		end
	end
end

local function destroystuff(inst)
	local pt = inst:GetPosition()
	local ents = TheSim:FindEntities(pt.x, pt.y, pt.z, 5)
	local heading_angle = -(inst.Transform:GetRotation())
	for k,v in pairs(ents) do
		if v and v.components.workable and v.components.workable.workleft > 0 and v.components.workable.action ~= ACTIONS.NET then
			SpawnPrefab("collapse_small").Transform:SetPosition(v:GetPosition():Get())
			v.components.workable:Destroy(inst)
		end
	end
end

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

local actionhandlers =
{
	ActionHandler(ACTIONS.GOHOME, "taunt"),
	ActionHandler(ACTIONS.ATTACK, "attack"),
	ActionHandler(ACTIONS.RUMMAGE, "action"),
	ActionHandler(ACTIONS.STORE, "steal"),
	ActionHandler(ACTIONS.EAT, "action2"),
	ActionHandler(ACTIONS.PICKUP, "action2"),
	ActionHandler(ACTIONS.PICK, "action2"),
	ActionHandler(ACTIONS.DROP, "action"),
	ActionHandler(ACTIONS.HARVEST, "action2"),
	ActionHandler(ACTIONS.HEAL, "action"),
	ActionHandler(ACTIONS.COMBINESTACK, "action"),
	ActionHandler(ACTIONS.UNWRAP, "action"),
	ActionHandler(ACTIONS.GIVE, "attack"),
	ActionHandler(ACTIONS.GIVETOPLAYER, "attack"),
	ActionHandler(ACTIONS.GIVEALLTOPLAYER, "attack"),
	ActionHandler(ACTIONS.TRAVEL, "action"),
	ActionHandler(ACTIONS.MIGRATE, "action"),
	ActionHandler(ACTIONS.ATTACK, "attack"),
	ActionHandler(ACTIONS.PET, "action"),
	ActionHandler(ACTIONS.ABANDON, "action"),
	ActionHandler(ACTIONS.WRAPBUNDLE, "action"),
}

local mobCraftActions =
{

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


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=
{
	CommonHandlers.OnLocomote(true,true),
	CommonHandlers.OnSleep(),
	CommonHandlers.OnFreeze(),
	CommonHandlers.OnDeath(),
	EventHandler("doattack", function(inst, data) inst.sg:GoToState("attack", data.target) end),
	EventHandler("attacked", function(inst) if not inst.components.health:IsDead() and not inst.sg:HasStateTag("attack") and not inst.sg:HasStateTag("busy") and inst.israged ~= nil and inst.israged == false then inst.sg:GoToState("hit") end end),
	EventHandler("ms_opengift",
        function(inst)
            if not inst.sg:HasStateTag("busy") then
                inst.sg:GoToState("opengift")
            end
        end),
}

local function ShakeIfClose(inst)
	for i, v in ipairs(AllPlayers) do
		v:ShakeCamera(CAMERASHAKE.FULL, .7, .02, .3, inst, 40)
	end
end

local function ShakeIfClose_Footstep(inst)
	for i, v in ipairs(AllPlayers) do
		v:ShakeCamera(CAMERASHAKE.FULL, .35, .02, 1.25, inst, 40)
	end
end

local function DoFootstep(inst)
	if inst:IsStandState("quad") then
		inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/step_soft")
	else
		inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/step_stomp")
		ShakeIfClose_Footstep(inst)
		--ShakeIfClose(inst)
		
	end
end

local states=
{

	State{
		name = "bi",
		tags = {"busy"},
		onenter = function(inst, data)
			inst.Physics:Stop()
			inst.sg.statemem.endstate = data.endstate
			inst.AnimState:PlayAnimation(data.customtrans or "taunt_pre")
		end,

		events =
		{
			EventHandler("animover", function(inst)
				inst:SetStandState("bi")
				--inst.components.locomotor:SetShouldRun(true)
				inst.sg:GoToState(inst.sg.statemem.endstate)
			end)
		},

		timeline=
		{
			TimeEvent(6*FRAMES, function(inst) PlayFootstep(inst) end),
		},
	},
	
	State{
        name = "opengift",
        tags = { "busy", "pausepredict" },

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

            inst.SoundEmitter:PlaySound("dontstarve/common/player_receives_gift")
            inst.AnimState:PlayAnimation("idle_loop", true)
            --inst.AnimState:PushAnimation("taunt", 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("taunt", true)
            end),
        },

        events =
        {
            EventHandler("firedamage", function(inst)
                --inst.AnimState:PlayAnimation("taunt")
                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 = "quad",
		tags = {"busy"},
		onenter = function(inst, data)
			inst.Physics:Stop()
			inst.sg.statemem.endstate = data.endstate
			inst.AnimState:PlayAnimation(data.customtrans or "taunt_pst")
		end,

		events =
		{
			EventHandler("animover", function(inst)
				inst:SetStandState("quad")
				--inst.components.locomotor:SetShouldRun(false)
				inst.sg:GoToState(inst.sg.statemem.endstate)
			end)
		},

		timeline=
		{
			TimeEvent(7*FRAMES, function(inst)
				inst:SetStandState("quad")
				DoFootstep(inst)
			end),
		},
	},

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

		onenter = function(inst)
			inst.Physics:Stop()
			inst.AnimState:PlayAnimation("idle_loop", true)
		end,

		timeline=
		{

		},
	},

----------------------COMBAT------------------------

	State{
		name = "targetstolen",
		tags = {"busy", "canrotate"},

		onenter = function(inst)
			inst.Physics:Stop()
			inst.AnimState:PlayAnimation("taunt")
		end,

		timeline=
		{
			TimeEvent(8*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/taunt") end),
			TimeEvent(9*FRAMES, function(inst) DoFootstep(inst) end),
			TimeEvent(33*FRAMES, function(inst) DoFootstep(inst) end),
		},

		events=
		{
			EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
		},
	},
	
	State{
		name = "rage",
		tags = {"busy", "canrotate"},

		onenter = function(inst)
			inst.AnimState:PlayAnimation("walk_pst")
			if inst.israged == true then
				inst.israged = false
			else	
			inst.Physics:Stop()
			inst.israged = true
			inst.sg:GoToState("targetstolen")
			end
		end,

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

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

		onenter = function(inst, cb)
			if inst.components.locomotor then
				inst.components.locomotor:StopMoving()
			end
			inst.AnimState:PlayAnimation("standing_hit")
		end,

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

	State{
		name = "attack",
		tags = {"attack", "busy", "canrotate"},

		onenter = function(inst)
			--if not inst.israged == true then
      
                inst.components.locomotor:StopMoving()
                
                inst.components.combat:StartAttack()
                inst.AnimState:PlayAnimation("atk")				
            
			--elseif inst.israged == true then
			--inst.sg:GoToState("pound")
			--end
        end,

		timeline=
		{
			TimeEvent(4*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/attack") end),
			--TimeEvent(15*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/attack") end),
			TimeEvent(28*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/swhoosh") end),
			TimeEvent(35*FRAMES, function(inst) inst:PerformBufferedAction() end),
		},


		events=
		{
			EventHandler("animqueueover", function(inst) inst.sg:GoToState("idle") end),
		},
	},
	
	State{
		name = "quick_attack",
		tags = {"attack", "busy", "canrotate"},

		onenter = function(inst)
      
                inst.components.locomotor:StopMoving()                
                inst.components.combat:StartAttack()
                inst.AnimState:PlayAnimation("atk")			
				inst.AnimState:SetTime(15* FRAMES)
        end,

		timeline=
		{
			TimeEvent(4*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/attack") end),
			--TimeEvent(15*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/attack") end),
			TimeEvent(13*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/swhoosh") end),
			TimeEvent(20*FRAMES, function(inst) inst:PerformBufferedAction() end),
		},


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

	State{
		name = "special_atk1",
		tags = {"attack", "busy"},

		onenter = function(inst)
		if inst.specialatk == false then
		 inst.sg:GoToState("idle")
		else 
			if inst.components.locomotor then
				inst.components.locomotor:StopMoving()
			end
			inst.AnimState:PlayAnimation("ground_pound")
			inst.AnimState:PushAnimation("taunt_pre", false)
		end	
		end,

		timeline=
		{
			TimeEvent(17*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/swhoosh") end),
			TimeEvent(20*FRAMES, function(inst)
				ShakeIfClose(inst)
				local isname = inst:GetDisplayName()
				local selfpos = inst:GetPosition()
				print("LOGGED: "..isname.." used ground pound at "..selfpos.x..","..selfpos.y..","..selfpos.z.." as "..inst.prefab)
				inst.components.groundpounder:GroundPound()
				inst.cangroundpound = false
				if not inst.components.timer:TimerExists("GroundPound") then
					inst.components.timer:StartTimer("GroundPound", 10)
				end
				inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/groundpound")
			end),
		},

		events=
		{
			EventHandler("animqueueover", function(inst)
				inst:SetStandState("quad")
				inst.specialatk = false
				inst:DoTaskInTime(10, function() inst.specialatk = true end)
				inst.sg:GoToState("idle")
			end),
		},
	},

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

		onenter = function(inst)
			if inst.components.locomotor then
				inst.components.locomotor:StopMoving()
			end
			inst.AnimState:PlayAnimation("death")
			inst.components.inventory:DropEverything(true)
			--inst.Physics:ClearCollisionMask()
			
		end,

		timeline=
		{
			TimeEvent(6*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/death") end),
			--TimeEvent(6*FRAMES, function(inst)inst.components.lootdropper:DropLoot(Vector3(inst.Transform:GetWorldPosition())) end),
			TimeEvent(50*FRAMES, function(inst)
				ShakeIfClose(inst)
				inst.components.lootdropper:DropLoot(Vector3(inst.Transform:GetWorldPosition()))
				inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/groundpound")
			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),
        },

	},

-------------------EATING-------------------------

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

		onenter = function(inst)
			inst.Physics:Stop()
			inst.AnimState:PlayAnimation("action")
			inst.AnimState:PushAnimation("eat_loop", false)
		end,

		onexit = function(inst)

		end,

		timeline=
		{
			TimeEvent(5*FRAMES, function(inst) end),
			TimeEvent(15*FRAMES, function(inst)
				inst:PerformBufferedAction()
				--inst.sg:RemoveStateTag("busy")
				--inst.sg:AddStateTag("wantstoeat")
				--inst.last_eat_time = GetTime()
			end),
			TimeEvent(14*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/gulp") end),
		},

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

			name = "action",
			tags = {"canrotate"},

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

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

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

		onenter = function(inst)
			inst.Physics:Stop()
			inst.AnimState:PushAnimation("eat_loop", true)
			local timeout = math.random()+.5
			local ba = inst:GetBufferedAction()
			if ba and ba.target and ba.target:HasTag("edible") then
					timeout = timeout*2
			inst.sg:SetTimeout(timeout)
			end
		end,

		timeline=
		{
			TimeEvent(3*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/chew") end),
			TimeEvent(10*FRAMES, function(inst) inst:PerformBufferedAction() end),
			TimeEvent(14*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/chew") end),
			TimeEvent(23*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/chew") end),
		},

		ontimeout = function(inst)
			local ba = inst:GetBufferedAction()
			inst:PerformBufferedAction()
			inst.last_eat_time = GetTime()
			inst.sg:GoToState("eat_pst")
		end,

	},

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

		onenter = function(inst)
			inst.Physics:Stop()
			inst.AnimState:PlayAnimation("eat_pst")
		end,

		timeline=
		{
		},

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

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

		onenter = function(inst)
			inst.Physics:Stop()
			inst.AnimState:PlayAnimation("atk", false)
		end,

		timeline=
		{
			TimeEvent(4*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/attack") end),
			--TimeEvent(15*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/attack") end),
			TimeEvent(28*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/swhoosh") end),
			TimeEvent(35*FRAMES, function(inst) inst:PerformBufferedAction() end),
		},

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

---------------------------WALKING---------------
-- the tags and names have been switched around to trick the game into making you "walk"

	State{
			name = "run_start",
			tags = {"moving", "running", "canrotate"},

			onenter = function(inst)
			if inst.israged == true and inst.components.hunger:GetPercent() > 0.5 then
				inst.components.locomotor:RunForward()
				inst.AnimState:PlayAnimation("charge_pre")
			elseif inst.israged == true and inst.components.hunger:GetPercent() <= 0.5 and GVG_MODE ~= "Disable" then
				inst.components.locomotor:RunForward()
				inst.AnimState:PlayAnimation("charge2_pre")
			else
				inst.components.locomotor:WalkForward()
				inst.AnimState:PlayAnimation("walk_pre")
			end
				--local anim = (inst.components.combat.target and not inst.components.combat.target:HasTag("beehive")) and "charge_pre" or "walk_pre"
				--inst.AnimState:PlayAnimation(anim)
			end,

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

	State{
			name = "run",
			tags = {"moving", "running", "canrotate"},

			onenter = function(inst)
				if inst.israged == true then
					inst.components.locomotor:RunForward()
					inst.AnimState:PlayAnimation("charge_loop")
				else
					inst.components.locomotor:WalkForward()
					inst.AnimState:PlayAnimation("walk_loop")
				end
				--local anim = (inst.components.combat.target and not inst.components.combat.target:HasTag("beehive")) and "charge_loop" or "walk_loop"
				--inst.AnimState:PlayAnimation(anim)
				--inst.components.locomotor:RunForward()
				if inst.israged == true then
					inst:DoTaskInTime(math.random(13)*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/grrrr") end)
				end
			end,

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

			timeline=
			{
				TimeEvent(2*FRAMES, function(inst)
					if inst.israged == true then
						DoFootstep(inst)
						ShakeIfClose(inst)
						
					end
				end),
				TimeEvent(18*FRAMES, function(inst)
					if inst.israged == true then
						DoFootstep(inst)
						ShakeIfClose(inst)
					end
				end),
				TimeEvent(4*FRAMES, function(inst)
					if not inst.israged == true then
						DoFootstep(inst)
						ShakeIfClose(inst)
					end
				end),
				TimeEvent(30*FRAMES, function(inst)
					if not inst.israged == true then
						DoFootstep(inst)
						ShakeIfClose(inst)
					end
				end),
			},
		},

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

			onenter = function(inst)
				inst.components.locomotor:StopMoving()
				--local anim = (inst.components.combat.target and not inst.components.combat.target:HasTag("beehive")) and "charge_pst" or "walk_pst"
				DoFootstep(inst)
				ShakeIfClose(inst)
				if inst.israged == true then
					inst.AnimState:PlayAnimation("charge_pst")
				else
					inst.AnimState:PlayAnimation("walk_pst")
				end
			end,

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

	State{
			name = "walk_start",
			tags = {"moving", "atk_pre", "canrotate"},

			onenter = function(inst)
				inst.components.locomotor:WalkForward()
				inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/taunt", "taunt")
				inst.AnimState:PlayAnimation("charge_pre")
			end,

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

	State{

			name = "walk",
			tags = {"moving", "canrotate"},

			onenter = function(inst)
				--inst.components.locomotor:WalkForward()
				if not inst.SoundEmitter:PlayingSound("taunt") then inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/taunt", "taunt") end
				inst.AnimState:PlayAnimation("charge_roar_loop")
			end,

			timeline=
			{
				TimeEvent(3*FRAMES, function(inst)
					DoFootstep(inst)
					destroystuff(inst)
				end),
				TimeEvent(11*FRAMES, function(inst)
					DoFootstep(inst)
					destroystuff(inst)
				end),
			},

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

	State{

			name = "walk_stop",
			tags = {"canrotate"},

			onenter = function(inst)
				inst.components.locomotor:StopMoving()
				--local should_softstop = false
				inst.AnimState:PlayAnimation("charge_pst")
			end,

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

------------------SLEEPING-----------------

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

			onenter = function(inst)
				
				inst.components.locomotor:StopMoving(true)
				--end
				--inst.components.locomotor:StopMoving()
				--inst.last_eat_time = nil -- Unset eat timer
				--if inst:IsStandState("quad") then
					--inst.AnimState:PushAnimation("sleep_pre", false)
				--else
				inst.AnimState:PlayAnimation("standing_sleep_pre")
				inst.AnimState:PushAnimation("sleep_pre", false)
			end,

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

			timeline=
			{
				TimeEvent(25*FRAMES, function(inst)
					if inst:IsStandState("bi") then
						inst:SetStandState("quad")
						DoFootstep(inst)
					end
				end),
			},
		},

		State{

			name = "sleeping",
			--tags = {"sleeping"},
			tags = {"sleeping"},
			onenter = function(inst)
				if inst.components.locomotor then
				inst.components.locomotor:StopMoving()
				end
				inst.Physics:Stop()
				inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/sleep")
				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(20, false)
				end
				inst.AnimState:PlayAnimation("sleep_loop")
				
			end,
			
			timeline =
		{
			TimeEvent(0*FRAMES, function(inst) inst.components.locomotor:StopMoving() end)
			--TimeEvent(15*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/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)
				--inst.last_eat_time = GetTime() -- Fake this as eating so he doesn't aggro immediately
				inst.components.locomotor:StopMoving()
				inst.AnimState:PlayAnimation("sleep_pst")
				inst.AnimState:PushAnimation("taunt_pre", false)
				if inst.components.sleeper and inst.components.sleeper:IsAsleep() then
					inst.components.sleeper:WakeUp()
				end
				if not inst:IsStandState("quad") then inst:SetStandState("quad") end
			end,

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

			timeline=
			{
				TimeEvent(27*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/bearger/taunt_short") end),
			},
		},
}

CommonStates.AddFrozenStates(states)

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

