require("stategraphs/commonstates")

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, "action"),
	ActionHandler(ACTIONS.DROP, "special_atk2"),
	ActionHandler(ACTIONS.EAT, "action"),
	ActionHandler(ACTIONS.HARVEST, "action"),
	ActionHandler(ACTIONS.FEED, "action"),
	ActionHandler(ACTIONS.PICK, "action"),
	ActionHandler(ACTIONS.COMBINESTACK, "action"),
	ActionHandler(ACTIONS.UNWRAP, "action"),
	--ActionHandler(ACTIONS.CHANGEIN, "attack"),
	ActionHandler(ACTIONS.ACTIVATE, "special_atk2"),	
	ActionHandler(ACTIONS.GIVE, "special_atk2"),
	ActionHandler(ACTIONS.GIVETOPLAYER, "special_atk2"),
	ActionHandler(ACTIONS.GIVEALLTOPLAYER, "special_atk2"),
	ActionHandler(ACTIONS.FEED, "action"),
	--ActionHandler(ACTIONS.JUMPIN, "eat"),
	--ActionHandler(ACTIONS.TRAVEL, "eat"),
	ActionHandler(ACTIONS.MIGRATE, "action"),
	
}

local mobCraftActions =
{
	ActionHandler(ACTIONS.GOHOME, "gohome"),
	ActionHandler(ACTIONS.ATTACK, "attack"),
	ActionHandler(ACTIONS.PICKUP, "action"),
	ActionHandler(ACTIONS.PICK, "action"),
	ActionHandler(ACTIONS.DROP, "special_atk2"),
	ActionHandler(ACTIONS.SLEEPIN, "sleep"),
	ActionHandler(ACTIONS.EAT, "action"),
	ActionHandler(ACTIONS.HEAL, "action"),
	ActionHandler(ACTIONS.FEED, "action"),
	ActionHandler(ACTIONS.FAN, "action"),
	ActionHandler(ACTIONS.DIG, "attack"),
	ActionHandler(ACTIONS.CHOP, "attack"),
	ActionHandler(ACTIONS.MINE, "attack"),
	ActionHandler(ACTIONS.COOK, "action"),
	ActionHandler(ACTIONS.FILL, "action"),
	ActionHandler(ACTIONS.DRY, "action"),
	ActionHandler(ACTIONS.ADDFUEL, "action"),
	ActionHandler(ACTIONS.ADDWETFUEL, "action"),
	ActionHandler(ACTIONS.ACTIVATE, "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, "special_atk2"),
	ActionHandler(ACTIONS.UNLOCK, "action"),
	ActionHandler(ACTIONS.TURNOFF, "special_atk2"),
	ActionHandler(ACTIONS.TURNON, "special_atk2"),
	ActionHandler(ACTIONS.SEW, "action"),
	ActionHandler(ACTIONS.COMBINESTACK, "action"),
	ActionHandler(ACTIONS.UPGRADE, "action"),
	ActionHandler(ACTIONS.WRITE, "action"),
	ActionHandler(ACTIONS.FEEDPLAYER, "special_atk2"),
	ActionHandler(ACTIONS.TERRAFORM, "special_atk2"),
	ActionHandler(ACTIONS.NET, "attack"),
	ActionHandler(ACTIONS.CHECKTRAP, "special_atk2"),
	ActionHandler(ACTIONS.SHAVE, "special_atk2"),
	ActionHandler(ACTIONS.FISH, "action"),
	ActionHandler(ACTIONS.REEL, "action"),
	ActionHandler(ACTIONS.CATCH, "action"),
	ActionHandler(ACTIONS.TEACH, "action"),
	ActionHandler(ACTIONS.MANUALEXTINGUISH, "special_atk2"),
	ActionHandler(ACTIONS.RESETMINE, "special_atk2"),
	ActionHandler(ACTIONS.BLINK, "special_atk2"),
	ActionHandler(ACTIONS.GIVE, "special_atk2"),
	ActionHandler(ACTIONS.GIVEALLTOPLAYER, "special_atk2"),
	--ActionHandler(ACTIONS.CHANGEIN, "changeskin"),
	ActionHandler(ACTIONS.SMOTHER, "special_atk2"),
	ActionHandler(ACTIONS.CASTSPELL, "special_atk2"),
	ActionHandler(ACTIONS.WRAPBUNDLE, "special_atk2"),
	ActionHandler(ACTIONS.UNWRAP, "special_atk2"),
	ActionHandler(ACTIONS.UNLOCK, "special_atk2"),
	ActionHandler(ACTIONS.USEKLAUSSACKKEY, "special_atk2"),
}


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") 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),
	EventHandler("locomote", function(inst) 
        if not inst.sg:HasStateTag("busy") then
            
            local is_moving = inst.sg:HasStateTag("moving")
            local wants_to_move = inst.components.locomotor:WantsToMoveForward()
			local should_move = inst.components.locomotor:WantsToMoveForward()
            if not inst.sg:HasStateTag("attack") and not (inst.sg:HasStateTag("home") or inst.sg:HasStateTag("sleeping")) and is_moving ~= wants_to_move then
                if wants_to_move then
                    inst.sg:GoToState("run_start")
                else
                    inst.sg:GoToState("run_stop")
                end
            end
			if inst.sg:HasStateTag("home") or inst.sg:HasStateTag("home_waking") then -- wakeup on locomote
            if inst.sleepingbag ~= nil and inst.sg:HasStateTag("sleeping") and inst.sg:HasStateTag("home") then
                inst.sleepingbag.components.sleepingbag:DoWakeUp()
                inst.sleepingbag = nil
				inst:Show()
				--inst.AnimState:PushAnimation("pig_pickup")
				SetSleeperAwakeState(inst)
				--inst.AnimState:PushAnimation("pig_pickup")
				inst.sg:GoToState("taunt")
				
            end end
        end
    end),    
    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, playanim)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("idle_loop", true)
            inst.sg:SetTimeout(math.random()*4+2)
            if inst.charged then
                inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jacobshorn")
            end
            inst.jacobsladdersfxtask = inst:DoPeriodicTask(44*FRAMES, function(inst)
                if inst.charged then
                    inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jacobshorn")
                end
            end)
        end,        
      
        ontimeout= function(inst)
            inst.sg:GoToState("bleet")
        end,

        onexit= function(inst)
            if inst.jacobsladdersfxtask then
                inst.jacobsladdersfxtask:Cancel()
                inst.jacobsladdersfxtask = nil
            end
        end,

        timeline = 
        { 
            TimeEvent(GetRandomWithVariance(8,3)*FRAMES, function(inst) 
                inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/chew")
            end),
            TimeEvent(GetRandomWithVariance(33,3)*FRAMES, function(inst) 
                inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/chew")
            end),
        },
		
		 events =
        {   
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end ),        
        },
    },


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

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

        events =
        {   
            EventHandler("animover", function(inst) inst.sg:GoToState("run") end ),        
        },
    },
        
    State{            
        name = "run",
        tags = {"moving", "canrotate"},
        
        onenter = function(inst) 
           -- inst.components.locomotor:WalkForward()
            inst.AnimState:PlayAnimation("walk")
            inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jump")
            if inst.charged then
                inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jacobshorn")
            end
        end,

        timeline = 
        { 
            TimeEvent(2*FRAMES, function(inst) 
                inst.components.locomotor:RunForward() 
            end),
            TimeEvent(14*FRAMES, function(inst) 
                inst.components.locomotor:WalkForward()
            end),
        },

        events=
        {   
            EventHandler("animover", function(inst) inst.sg:GoToState("run") end ),        
        },
    },      
    
    State{            
        name = "run_stop",
        tags = {"idle", "canrotate"},
        
        onenter = function(inst) 
        inst.components.locomotor:StopMoving()
            inst.AnimState:PlayAnimation("walk_pst", false)
        end,

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

    State{
        name = "special_atk1",
        tags = {"busy"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("taunt_pre")
            inst.AnimState:PushAnimation("taunt")
			inst:PerformBufferedAction()
            inst.AnimState:PushAnimation("taunt_pst", false)

        end,
        
        timeline=
        {
            TimeEvent(5*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/taunt") end),
            TimeEvent(17*FRAMES, function(inst) if inst.charged then inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jacobshorn") end end),
            TimeEvent(27*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/hoof") end),
            TimeEvent(44*FRAMES, function(inst) if inst.charged then inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jacobshorn") end end),
            TimeEvent(53*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/hoof") end),
            TimeEvent(71*FRAMES, function(inst) if inst.charged then inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jacobshorn") end end),
            TimeEvent(79*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/hoof") end),
        },
        
        events=
        {
            EventHandler("animqueueover", function(inst) inst.sg:GoToState("idle") end),
        },
    },

    State{
        name = "special_atk2",
        tags = {"busy"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("bleet")
			inst:PerformBufferedAction()
        end,
        
        timeline=
        {
            TimeEvent(1*FRAMES, function(inst)
                if inst.charged then
                    inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jacobshorn")
                end
            end),
            TimeEvent(10*FRAMES, function(inst) 
                inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/bleet")
            end)
        },
        
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
        },
    },

    State{
        name = "discharge",
        tags = {"busy"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("trans")
            inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/shocked_electric")
        end,
        
        timeline=
        {
            TimeEvent(18*FRAMES, function(inst) 
                inst.AnimState:Hide("fx") 
				if inst.isshiny == 0 then 
                inst.AnimState:SetBuild("lightning_goat_build")
				elseif inst.isshiny > 0 then
				inst.AnimState:SetBuild("lightning_goat_shiny_build_0"..inst.isshiny)
				end
            end)
        },
        
        events=
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") end),
        },
    },

    State{
        name = "shocked",
        tags = {"busy"},
        
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("shock")
            inst.AnimState:PushAnimation("shock_pst", false)
            inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/shocked_electric")
            inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/shocked_bleet")
            inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jacobshorn")
        end,
        
        timeline=
        {
            TimeEvent(10*FRAMES, function(inst) 
                inst:PerformBufferedAction()
            end)
        },
        
        events=
        {
            EventHandler("animqueueover", 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:PlayAnimation("atk", false)
        end,
        

		timeline = 
    {
        TimeEvent(1*FRAMES, function(inst)
            if inst.charged then
                inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jacobshorn")
            end
        end),
        TimeEvent(9*FRAMES, function(inst)
            inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/headbutt")
        end),
        TimeEvent(12*FRAMES, function(inst)
            if inst.charged then
                inst:PerformBufferedAction()
            else
                inst:PerformBufferedAction()
            end
        end),
        TimeEvent(15*FRAMES, function(inst) inst.sg:RemoveStateTag("attack") end),
    },
		
        
        events=
        {
            EventHandler("animqueueover", function(inst) inst.sg:GoToState("idle") end),
        },
    },
	
	State{
        name = "hit",
        tags = {"hit"},
        
        onenter = function(inst, cb)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("hit", false)
        end,
        
		timeline = 
		{
			
		},
        
        events=
        {
            EventHandler("animqueueover", function(inst) inst.sg:GoToState("idle") end),
        },
    },
	
	State{
        
        name = "action",
        onenter = function(inst, playanim)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("walk_pst")
        end,
        
		timeline =
        {
            TimeEvent(5 * FRAMES, function(inst)
                inst:PerformBufferedAction()
            end),
        },
		
        events = 
        {
            EventHandler("animover", function(inst) inst.sg:GoToState("idle") 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_loop", true)
            ----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(9*FRAMES, function(inst)
            if inst.charged then
                inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jacobshorn")
            end
        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(8, false)
				end
				inst.AnimState:PlayAnimation("sleep_loop")
			end,

        
		timeline = 
		{
        TimeEvent(41*FRAMES, function(inst)
            inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/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,
		
        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)
			
            if inst.components.playercontroller ~= nil then
                inst.components.playercontroller:RemotePausePrediction()
            end
        end,
		
		timeline = 
		{
        TimeEvent(0*FRAMES, function(inst)
            inst:AddTag("dead")
            inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/death")
        end),
        TimeEvent(3*FRAMES, function(inst)
            if inst.charged then
                inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/lightninggoat/jacobshorn")
            end
        end),
        TimeEvent(34*FRAMES, function(inst)
            inst.Light:Enable(false)
            inst.AnimState:ClearBloomEffectHandle()
        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),
        },
    },

	
}

--[[
CommonStates.AddCombatStates(states,
{
    attacktimeline = 
    {
        TimeEvent(15*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/knight"..inst.kind.."/attack") end),
        TimeEvent(17*FRAMES, function(inst) inst:PerformBufferedAction() end),
    },
    hittimeline = 
    {
        TimeEvent(0*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/knight"..inst.kind.."/hurt") end),
    },
})]]
  

CommonStates.AddFrozenStates(states)
    



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

