local brain = require "brains/summonfranbrain"

local assets = {
	Asset("ATLAS", "images/inventoryimages/franjournal.xml"),
    Asset("ANIM", "anim/swap_pickaxe.zip"),
    Asset("ANIM", "anim/swap_axe.zip"),
    Asset("ANIM", "anim/swap_nightmaresword.zip"),
}

local items =
{
    AXE = "swap_axe",
    PICK = "swap_pickaxe",
    SWORD = "swap_nightmaresword",
}

local prefabs = {
	"fran",
	"clonefranspear",
	"bloodswordx",
}

local function ShouldAcceptItem(inst, item)
	local currenthealth = inst.components.health.currenthealth / inst.components.health.maxhealth
	if item.components.edible and currenthealth < 1 and item.components.edible.healthvalue > 0 then
		return true
	end
	if item.components.equippable and 
	(item.components.equippable.equipslot == EQUIPSLOTS.HEAD or 
	item.components.equippable.equipslot == EQUIPSLOTS.HANDS or 
item.components.equippable.equipslot == EQUIPSLOTS.BODY) and 
	not item.components.projectile then
		if item.prefab == "batbat" then
			print("refusing batbat")
			return false
		end
		return true
	end
end

local function OnGetItemFromPlayer(inst, giver, item)
	if item.components.equippable and 
	(item.components.equippable.equipslot == EQUIPSLOTS.HEAD or 
	item.components.equippable.equipslot == EQUIPSLOTS.HANDS or 
	item.components.equippable.equipslot == EQUIPSLOTS.BODY) then     
		local newslot = item.components.equippable.equipslot
		local current = inst.components.inventory:GetEquippedItem(newslot)
		if current then
			inst.components.inventory:DropItem(current)
		end      
		inst.components.inventory:Equip(item)
	elseif item.components.edible then
		inst.components.health:DoDelta(item.components.edible:GetHunger(inst), nil, item.prefab)
		inst:PushEvent("oneatsomething", {food = item})
		inst.sg:GoToState("eat")
	end
end

local function OnRefuseItem(inst, item)
	inst.sg:GoToState("refuse")
	inst.components.talker:Say("No.")
end

local function die(inst)
    inst.components.health:Kill()
end

local function onsave(inst, data)
    data.timeleft = (0)
end

local function entitydeathfn(inst, data)
    if data.inst:HasTag("player") then
        inst:DoTaskInTime(math.random(), function() inst.components.health:Kill() end)
    end
end

local common_postinit = function(inst)
    inst:AddComponent("sanityaura")
    inst.components.sanityaura.aura = TUNING.SANITYAURA_SMALL
end

local function NormalRetargetFn(inst)
        return FindEntity(inst, TUNING.PIG_TARGET_DIST, function(guy)
                return guy:HasTag("monster") and guy.components.health and not guy.components.health:IsDead()
                and inst.components.combat:CanTarget(guy)
        end, nil, { "character" }, nil)
end

local function linkToBuilder(inst, builder)
	if not builder.components.leader then
		builder:AddComponent("leader")
	end
	builder.components.leader:AddFollower(inst, true)
end

local function OnAttacked(inst, data)
	local attacker = data.attacker
    inst.components.combat:SetTarget(attacker)
    inst.components.combat:ShareTarget(attacker, 30, function(dude)
		return dude:HasTag("summonedbyplayer") and dude.components.follower.leader == inst.components.follower.leader
	end, 5)
end

local function OnAttackOther(inst, data)
	local target = data.target
	inst.components.combat:ShareTarget(target, 30, function(dude)
		return dude:HasTag("summonedbyplayer") and dude.components.follower.leader == inst.components.follower.leader
	end, 5)
end

local function fn()
	local inst = CreateEntity()
	inst.entity:AddTransform()
	inst.entity:AddAnimState()
	inst.entity:AddMiniMapEntity()
	inst.entity:AddSoundEmitter()
	inst.entity:AddDynamicShadow()
	inst.entity:AddNetwork()
	
	MakeCharacterPhysics(inst, 30, .3)
	
	inst.DynamicShadow:SetSize(2, 1.5)
	
	inst.Transform:SetFourFaced()
	inst.Transform:SetScale(1, 1, 1)

	inst.AnimState:SetBank("wilson")
	inst.AnimState:SetBuild("fran")
	inst.AnimState:PlayAnimation("idle_loop", true)
	inst.AnimState:Hide("ARM_carry")
	inst.AnimState:Show("ARM_normal")
	
    inst.MiniMapEntity:SetIcon("franjournal.tex")
    inst.MiniMapEntity:SetPriority(4)
	
	inst:AddTag("summonfran")
	inst:AddTag("sheltercarrier")
	inst:AddTag("summonedbyplayer")
	inst:AddTag("scarytoprey")
	inst:AddTag("NOCLICK")

	inst.entity:SetPristine()

	if not TheWorld.ismastersim then
		return inst
	end
	
	MakeMediumBurnableCharacter(inst, "pig_torso")
	
	inst:AddComponent("francracker")
	
	inst:AddComponent("combat")
	inst.components.combat:SetDefaultDamage(TUNING.UNARMED_DAMAGE)
	inst.components.combat:SetAttackPeriod(2)
	inst.components.combat:SetRetargetFunction(3, NormalRetargetFn)
	
	local self = inst.components.combat
	local old = self.GetAttacked
	function self:GetAttacked(attacker, damage, weapon, stimuli)
		if attacker and attacker.prefab == "tentacle" then
			return true
		end
		return old(self, attacker, damage, weapon, stimuli)
	end
	
	inst:AddComponent("follower")
	
	inst:AddComponent("health")
	inst.components.health:SetMaxHealth(495)
	inst.components.health:StartRegen(1, 1)
	inst.components.health.absorb = 0.50
	inst.components.health.fire_damage_scale = 0
	
	inst:AddComponent("inspectable")




	inst:AddComponent("inventory")
	inst.bloodswordx = SpawnPrefab( "bloodswordx" )

	if inst.bloodswordx ~= nil then
		inst.components.inventory:Equip( inst.bloodswordx )
	end
	
	inst:AddComponent("locomotor")
	inst.components.locomotor.runspeed = 5
	inst.components.locomotor.walkspeed = 5
	
	inst:AddComponent("lootdropper")
	
	inst:AddComponent("talker")
	inst.components.talker:StopIgnoringAll()
	
	inst:AddComponent("trader")
	inst.components.trader:SetAcceptTest(ShouldAcceptItem)
	inst.components.trader.deleteitemonaccept = false
	inst.components.trader.onaccept = OnGetItemFromPlayer
	inst.components.trader.onrefuse = OnRefuseItem
	inst.components.trader:Enable()
	
	inst:AddComponent("perishable")
	inst.components.perishable:SetPerishTime(TUNING.PERISH_SUPERFAST)
	inst.components.perishable:StartPerishing()
    inst.components.perishable:SetOnPerishFn(inst.Remove)

    inst.lifetime = TUNING.SHADOWWAXWELL_LIFETIME
    inst.death = inst:DoTaskInTime(495, die)

	inst:SetBrain(brain)
	inst:SetStateGraph("SGsummonfran")

	inst:WatchWorldState("startnight", function()  
		inst.components.health:DoDelta(-10)  
	end)

	inst.OnBuilt = linkToBuilder
	
	inst:ListenForEvent("attacked", OnAttacked)  
	inst:ListenForEvent("onattackother", OnAttackOther)

	return inst
end

return Prefab("common/summonfran", fn, assets, prefabs)
