local brain = require "brains/suofeiya_fenshen_brain"

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 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(0.8, 0.8, 0.8)

	inst.AnimState:SetBank("wilson")
	inst.AnimState:SetBuild("suofeiya")
	inst.AnimState:PlayAnimation("idle_loop", true)
	inst.AnimState:Show("ARM_carry")
	inst.AnimState:Hide("ARM_normal")
	inst.AnimState:OverrideSymbol("swap_object", "swap_huanxiang", "swap_huanxiang")
	
	inst:AddTag("suofeiya_part")
	
	inst.entity:SetPristine()

	if not TheWorld.ismastersim then
		return inst
	end
	
	inst.persists = false
	
	inst:AddComponent("combat")
	inst.components.combat:SetDefaultDamage(40)
	inst.components.combat:SetAttackPeriod(2)
	inst.components.combat:SetRetargetFunction(3, NormalRetargetFn)
	
	inst:AddComponent("follower")
	
	inst:AddComponent("health")
	inst.components.health:SetMaxHealth(99999999)
	inst.components.health.absorb = 1
	inst.components.health.fire_damage_scale = 0
	inst.components.health.invincible = true
	
	inst:AddComponent("inspectable")
	
	inst:AddComponent("locomotor")
	inst.components.locomotor.runspeed = 7
	inst.components.locomotor.walkspeed = 7

	inst:SetBrain(brain)
	inst:SetStateGraph("SGsuofeiya_fenshen")
	
	inst:DoPeriodicTask(20, function()
		--±ù¶³
		local x,y,z = inst.Transform:GetWorldPosition()
		local ents = TheSim:FindEntities(x,y,z,6)
		for k,v in pairs(ents) do
			if v and v.components.freezable and 
				v.components.health and not v.components.health:IsDead() and
				( v:HasTag("hostile") or v:HasTag("monster") or v:HasTag("epic") or (v.components.combat and v.components.combat.target == inst ) )
			then
				v.components.freezable:AddColdness(6)
				v.components.freezable:SpawnShatterFX()
			end
		end
	end)
	
	inst:DoTaskInTime(20, function()
		--[[
		if inst and inst.components.health then
			inst.components.health:Kill()
		end]]
		if inst then
			inst:Remove()
		end
	end)

	return inst
end

return Prefab("suofeiya_fenshen", fn)
