require("stategraphs/commonstates")

local actionhandlers = 
{
    ActionHandler(ACTIONS.ATTACK, "attack"),
	ActionHandler(ACTIONS.EAT, "eat"),
    --ActionHandler(ACTIONS.PICKUP, "eat"),
}


local events =
{
    CommonHandlers.OnStep(),
    CommonHandlers.OnLocomote(true,true),
    CommonHandlers.OnSleep(),
    CommonHandlers.OnFreeze(),
    CommonHandlers.OnAttack(),
    CommonHandlers.OnAttacked(),
    CommonHandlers.OnDeath(),
    EventHandler("transformwere", function(inst) if not inst.components.health:IsDead() then inst.sg:GoToState("transformWere") end end),
    EventHandler("giveuptarget", function(inst, data) if data.target then inst.sg:GoToState("howl") end end),
    EventHandler("newcombattarget", function(inst, data)
        if data.target and not inst.sg:HasStateTag("busy") then
            if math.random() < 0.3 then
                inst.sg:GoToState("howl")
            else
                inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/idle")
            end
        end
    end),
}

local states=
{


	State{
        name = "death",
        tags = {"busy", "pausepredict", "nomorph"},
        
        onenter = function(inst)
            inst.components.locomotor:Stop()
            inst.components.locomotor:Clear()
            inst:ClearBufferedAction()

            inst.AnimState:PlayAnimation("death")
			--inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_howl")
			inst.components.inventory:DropEverything(true)
			--inst.components.lootdropper:DropLoot(inst:GetPosition())

            if inst.components.playercontroller ~= nil then
                inst.components.playercontroller:RemotePausePrediction()
            end
        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 = "howl",
		tags = {"busy"},
		
		onenter = function(inst)
			inst.Physics:Stop()
			inst.AnimState:PlayAnimation("howl")
		end,
		
		timeline = 
		{
			TimeEvent(20*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/howl") end),
		},
		
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
        },
	},
	
    State{
		name = "transformWere",
		tags = {"transform", "busy"},
		
		onenter = function(inst)
			inst.Physics:Stop()
			inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/transformToWere")
			if inst:HasTag("guard") then
				inst.AnimState:SetBuild("pig_guard_build")
			else
				if inst.isshiny == 0 then
				inst.AnimState:SetBuild("pig_build")
				else
				inst.AnimState:SetBuild("pig_shiny_build_0"..inst.isshiny)
				end
			end	
			inst.AnimState:PlayAnimation("transform_pig_were")
			inst:AddTag("hostile")

		end,
		
		onexit = function(inst)
            inst.AnimState:SetBuild("werepig_build")
		end,
		
        events=
        {
            EventHandler("animover", function(inst)
                --inst.components.sleeper:WakeUp()
                inst.sg:GoToState("howl")
            end ),
			EventHandler("attacked", function(inst)
	            inst.sg:GoToState("hit")
		    end),
            
        },        
    },
    
	State{
        name = "idle",
        tags = {"idle", "canrotate"},
        
        onenter = function(inst, pushanim)
            inst.Physics:Stop()
            if pushanim then
                if type(pushanim) == "string" then
                    inst.AnimState:PlayAnimation(pushanim)
                end
                inst.AnimState:PushAnimation("were_idle_loop", true)
            else
                inst.AnimState:PlayAnimation("were_idle_loop", true)
            end
        end,
    },
    
    State{
        name = "attack",
        tags = {"attack", "busy"},
        
        onenter = function(inst)
            
            local buffaction = inst:GetBufferedAction()
        local target = buffaction ~= nil and buffaction.target or nil
        inst.components.combat:SetTarget(target)
        inst.components.combat:StartAttack()
        inst.components.locomotor:Stop()
        inst.Physics:Stop()
        inst.AnimState:PlayAnimation("were_atk_pre")
        inst.AnimState:PushAnimation("were_atk", false)
        if target ~= nil then
            if target:IsValid() then
                inst:FacePoint(target:GetPosition())
                inst.sg.statemem.attacktarget = target
				end
			end
        end,
        
        timeline=
        {
            TimeEvent(15*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/attack") end),
            TimeEvent(16*FRAMES, function(inst) inst:PerformBufferedAction() end),
        },
        
        events=
        {
            EventHandler("animqueueover", function(inst)
                --if not inst.components.combat.target and math.random() < 0.3 then
                    --inst.sg:GoToState("howl")
               -- else
                    inst.sg:GoToState("idle")
            end ),
        },
    },
    
	State{
		name = "run_start",
		tags = {"moving", "running", "canrotate"},
	    
		onenter = function(inst) 
			inst.components.locomotor:RunForward()
			inst.AnimState:PlayAnimation("were_run_pre")
		end,

		events=
		{   
			EventHandler("animover", function(inst) inst.sg:GoToState("run") end ),        
		},
	},
    
	State{
		name = "run",
		tags = {"moving", "running", "canrotate"},
	    
        onenter = function(inst) 
            inst.components.locomotor:RunForward()
            if not inst.AnimState:IsCurrentAnimation("were_run_loop") then
                inst.AnimState:PlayAnimation("were_run_loop", true)
            end
            inst.sg:SetTimeout(inst.AnimState:GetCurrentAnimationLength())
        end,
	    
		timeline = 
		{
		    TimeEvent(0*FRAMES, PlayFootstep ),
		    TimeEvent(10*FRAMES, PlayFootstep ),
		},
		
		
		ontimeout = function(inst)
		    inst.sg:GoToState("run")
		end,
	},
        
	State{
		name = "run_stop",
		tags = {"canrotate"},
	    
		onenter = function(inst) 
			inst.Physics:Stop()
			inst.AnimState:PlayAnimation("were_run_pst")
		end,
	    
		events=
		{   
			EventHandler("animover", function(inst) inst.sg:GoToState("idle") end ),        
		},
	},
	
	State{
		name = "walk_start",
		tags = {"moving", "canrotate"},
	    
		onenter = function(inst) 
			inst.components.locomotor:WalkForward()
			inst.AnimState:PlayAnimation("were_walk_pre")
		end,

		events=
		{   
			EventHandler("animover", function(inst) inst.sg:GoToState("walk") end ),        
		},
	},
        
	State{
		name = "walk",
		tags = {"moving", "canrotate"},
	    
		onenter = function(inst) 
			inst.components.locomotor:WalkForward()
			inst.AnimState:PlayAnimation("were_walk_loop")
		end,
		
		timeline = 
		{
		    TimeEvent(0*FRAMES, PlayFootstep),
		    TimeEvent(12*FRAMES, PlayFootstep),
		},
		
		events=
		{   
			EventHandler("animover", function(inst) inst.sg:GoToState("walk") end ),        
		},
	},
    
	State{
		name = "walk_stop",
		tags = {"canrotate"},
	    
		onenter = function(inst) 
			inst.Physics:Stop()
			inst.AnimState:PlayAnimation("were_walk_pst")
		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("eat")
        end,
        
        timeline=
        {
            TimeEvent(20*FRAMES, function(inst) inst:PerformBufferedAction() end),
        },
        
        events=
        {
            EventHandler("animover", function(inst)
                if not inst.components.combat.target or math.random() < 0.3 then
                    inst.sg:GoToState("howl")
                else
                    inst.sg:GoToState("idle")
                end
            end ),
        },        
    },
    State{
        name = "hit",
        tags = {"busy"},
        
        onenter = function(inst)
            inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/hurt")
            inst.AnimState:PlayAnimation("hit")
            inst.Physics:Stop()            
        end,
        
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end ),
        },        
    },    
}

CommonStates.AddSleepStates(states,
{
	sleeptimeline = 
	{
		TimeEvent(35*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/werepig/sleep") end ),
	},
})

CommonStates.AddFrozenStates(states)
CommonStates.AddSimpleActionState(states, "eat", "eat", 20*FRAMES, {"busy"})
    
return StateGraph("werepigplayer", states, events, "idle", actionhandlers)

