require("stategraphs/commonstates")

local actionhandlers = 
{ 
	
	ActionHandler(ACTIONS.FAN, "appear"), 
    ActionHandler(ACTIONS.GOHOME, "action"),
	--ActionHandler(ACTIONS.ATTACK, "haunted"),
	ActionHandler(ACTIONS.PICKUP, "action"),
	ActionHandler(ACTIONS.DROP, "action"),
	--ActionHandler(ACTIONS.EAT, "eat"),
	ActionHandler(ACTIONS.HEAL, "action"),
	ActionHandler(ACTIONS.FEED, "action"),
	--ActionHandler(ACTIONS.FAN, "appear"),
	--ActionHandler(ACTIONS.SLEEPIN, "dissipate"),
	ActionHandler(ACTIONS.UNWRAP, "action"),
	ActionHandler(ACTIONS.PICK, "action"),
	ActionHandler(ACTIONS.DIG, "action"),
	ActionHandler(ACTIONS.CHOP, "action"),
	ActionHandler(ACTIONS.MINE, "action"),
	ActionHandler(ACTIONS.INVESTIGATE, "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.HARVEST, "action"),
	ActionHandler(ACTIONS.STORE, "action"),
	ActionHandler(ACTIONS.RUMMAGE, "action"),
	ActionHandler(ACTIONS.DEPLOY, "action"),
	ActionHandler(ACTIONS.HAMMER, "action"),
	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.ACTIVATE, "action"),	
	ActionHandler(ACTIONS.WRITE, "action"),
	ActionHandler(ACTIONS.GIVE, "action"),
	ActionHandler(ACTIONS.GIVETOPLAYER, "action"),
	ActionHandler(ACTIONS.FEEDPLAYER, "action"),
	ActionHandler(ACTIONS.TERRAFORM, "action"),
	ActionHandler(ACTIONS.GIVEALLTOPLAYER, "action"),
	ActionHandler(ACTIONS.JUMPIN, "action"),
	ActionHandler(ACTIONS.MIGRATE, "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.MANUALEXTINGUISH, "action"),
	ActionHandler(ACTIONS.EXTINGUISH, "action"),
	ActionHandler(ACTIONS.RESETMINE, "action"),
	ActionHandler(ACTIONS.BLINK, "action"),
	---PetActions--
	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 function CannotExamine(inst)
    return false
end

local function startaura(inst)
    inst.Light:SetColour(255/255, 32/255, 32/255)
    if inst:HasTag("girl") then
        inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_girl_attack_LP", "angry")
    else
        inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_attack_LP", "angry")
    end
	--inst.components.health:DoDelta(3, false)
    inst.AnimState:SetMultColour(207/255,92/255,92/255,1)

end

local function stopaura(inst)
    inst.Light:SetColour(180/255, 195/255, 225/255)
    inst.SoundEmitter:KillSound("angry")
    inst.AnimState:SetMultColour(1,1,1,1)
end



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),
	EventHandler("startaura", startaura),
    EventHandler("stopaura", stopaura),
    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 function getidleanim(inst)
    if inst.components.combat.target then
        return "angry"
    elseif inst.components.health:GetPercent() < .25 then
        return "shy"
    else
        return "idle"
    end
end

local states =
{
    State
    {
        name = "idle",
        tags = {"idle", "canrotate", "canslide"},
        onenter = function(inst)
            inst.AnimState:PlayAnimation(getidleanim(inst), true)
        end,
    },
	
	State
    {
        name = "action",
        tags = {"busy"},
        onenter = function(inst)
		if inst.specialsleep == false then
			inst.sg:GoToState("idle")
		end	
            inst.AnimState:PlayAnimation(getidleanim(inst), true)
        end,
		
		timeline=
        {
			--TimeEvent(14*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/hound/bite") end),
			TimeEvent(14*FRAMES, function(inst) 
			if inst:HasTag("invisible") then 
				inst.sg:GoToState("idle", true) 
			else 
				inst:PerformBufferedAction()  
				inst.sg:GoToState("idle", true) 
				end 
			end),
        },
    },
	
	State
    {
        name = "action2",
        tags = {"busy"},
        onenter = function(inst)
            --inst.AnimState:PlayAnimation(getidleanim(inst), true)
        end,
		
		timeline=
        {
			--TimeEvent(14*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/hound/bite") end),
			--TimeEvent(14*FRAMES, function(inst) inst:PerformBufferedAction()  inst.sg:GoToState("idle", true) 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", 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 = "special_wake",
		tags = {"busy"},
        onenter = function(inst)
			--print ("A wild ghost appears")
			inst:Show()
			inst.components.health:SetInvincible(false)
			--inst.HUD:Hide(false)
            inst.AnimState:PlayAnimation("appear")
			inst.specialsleep = true
			inst.Light:Enable(true)
			inst:RemoveTag("invisible")
			inst:RemoveTag("notarget")
			inst:AddTag("scarytoprey") 
            if inst:HasTag("girl") then
                inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_girl_howl")
            else
                inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_howl")
            end
			inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_howl_LP", "howl")
        end,

        events =
        {
            EventHandler("animover", function(inst)
                if inst.AnimState:AnimDone() then
                    inst.components.aura:Enable(true)
                    inst.sg:GoToState("idle")
					inst.CanExamine = nil
                end
            end),
        },
    },    
    
    State{
        name = "hit",
        tags = {"canrotate", "canslide"},
        
        onenter = function(inst)
            if inst:HasTag("girl") then
                inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_girl_howl")
            else
                inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_howl")
            end

            inst.AnimState:PlayAnimation("hit")
            --inst.Physics:Stop()            
        end,
        
        events =
        {
            EventHandler("animover", function(inst)
                if inst.AnimState:AnimDone() then
                    inst.sg:GoToState("idle")
                end
            end),
        },
    },

    State{
        name = "haunted",
        tags = {"busy"},
        
        onenter = function(inst)
            if inst:HasTag("girl") then
                inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_girl_attack_LP", "haunted")
            else
                inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_attack_LP", "haunted")
            end
                
            inst.AnimState:PlayAnimation("angry")
            inst.Physics:Stop()     
			inst.components.health:DoDelta(3, false)
        end,

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

        onexit = function(inst)
            inst.SoundEmitter:KillSound("haunted")
        end
    },

    State
    {
        name = "special_sleep",
		tags = {"busy", "hiding"},
        onenter = function(inst)
            inst.Physics:Stop()
            inst.AnimState:PlayAnimation("dissipate")
			inst:AddTag("invisible")
			inst:AddTag("notarget")
			inst.components.health:SetInvincible(true)
			inst:RemoveTag("scarytoprey") 
            if inst:HasTag("girl") then
                inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_girl_howl")
            else
                inst.SoundEmitter:PlaySound("dontstarve/ghost/ghost_howl")
            end
			inst.SoundEmitter:KillSound("howl")
			inst.Light:Enable(false)
			inst.components.aura:Enable(false)            
        end,
		
		events =
        {
            EventHandler("animover", function(inst)
                if inst.AnimState:AnimDone() then
					inst.components.aura:Enable(false)
					inst:Hide()
					inst.specialsleep = false
					inst.sg:GoToState("idle")					
                end
            end),
        },

        
    },
	
	    State
    {
        name = "sleeping",
		tags = {"idle", "canrotate", "canslide", "specialsleep"},
        onenter = function(inst)
            --inst.Physics:Stop()
            --inst.AnimState:PlayAnimation("dissipate")
			inst:AddTag("shadowcreature")
			inst:AddTag("invisible")
			inst:AddTag("shadow")
			inst:RemoveTag("scarytoprey") 
				
            
        end,

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

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

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

            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),
        },
	},	
}


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

]]
CommonStates.AddSimpleWalkStates(states, getidleanim)
CommonStates.AddSimpleRunStates(states, getidleanim)

CommonStates.AddSimpleActionState(states,"pickup", "attack", 14*FRAMES, {"busy"})



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

