local MakePlayerCharacter = require "prefabs/player_common"

local assets = 
{
	Asset("ANIM", "anim/hound_ice_shiny_build_01.zip"),
	Asset("ANIM", "anim/hound_ice_shiny_build_02.zip"),
}
local prefabs = {
	"houndstooth",
    "monstermeat",
    "redgem",
    "bluegem",
    }
	
local start_inv = {
	"houndstooth",
	"houndstooth",
	--"monstermeat",
}

local start_inv2 = 
{
	"houndstooth",
	"houndstooth",
	"houndhome",
}

if MOBHOUSE == "Enable1" or MOBHOUSE == "Enable3" then
	start_inv = start_inv2
end

SetSharedLootTable( 'houndiceplayer',
{
	{'monstermeat',			 1.00},
	{'houndstooth',			 0.50},
	{'houndstooth',			 0.50},
	{'bluegem',			 	 0.25},
	
})

local function CanShareTarget(dude)
    return dude:HasTag("hound")
        and not dude:IsInLimbo()
        and not (dude.components.health:IsDead() or dude:HasTag("player"))
end

local function OnAttacked(inst, data)
        inst.components.combat:SetTarget(data.attacker)
        inst.components.combat:ShareTarget(data.attacker, 30, CanShareTarget, 5)
 end


local function RestoreNightvision(inst)

	inst:DoTaskInTime(3, function(inst) 
	inst.Light:Enable(true)
	inst.Light:SetRadius(0)
	inst.Light:SetFalloff(.1)
	inst.Light:SetIntensity(.1)
	inst.Light:SetColour(245/255,40/255,0/255)
	end, inst)
end

------------------------------------------------------
----PvP Teleport----

local function getwildposition(inst)
    local ground = TheWorld
    local centers = {}
    for i, node in ipairs(ground.topology.nodes) do
        if ground.Map:IsPassableAtPoint(node.x, 0, node.y) then
            table.insert(centers, {x = node.x, z = node.y})
        end
    end
    if #centers > 0 then
        local pos = centers[math.random(#centers)]
        return Point(pos.x, 0, pos.z)
    else
        return inst:GetPosition()
    end
end

local function PvPTeleport(inst)
if inst.mobteleported == nil or inst.mobteleported == false then
	local ground = TheWorld
	local pt = getwildposition(inst)--Point(inst.Transform:GetWorldPosition())
      if pt.y <= .1 then
         pt.y = 0
         inst.Physics:Stop()
         inst.Physics:Teleport(pt.x,pt.y,pt.z)
		 inst.mobteleported = true
      end
	end
end

------------------------------------------------------
local function SetSkinOverride(inst) --despite the name, it only overrides if there is no other skin applied.
	if inst.isshiny == 2 then
		inst.AnimState:SetBuild("hound_ice_shiny_build_02")
		inst.components.health:SetAbsorptionAmount(0.25) -- damage resistance
		inst:SetStateGraph("SGhound_chainedp")
	end	
end



------------------------------------------------------
 local function OnLoad(inst, data)
	if data ~= nil then
		inst.mobteleported = data.mobteleported or false
		inst.isshiny = data.isshiny or 0
		SetSkinOverride(inst)
	end
end

local function OnSave(inst, data)
	data.mobteleported = inst.mobteleported or false
	data.isshiny = inst.isshiny or 0
end
------------------------------------------------------
local function setSkin(inst)
	if not inst:HasTag("playerghost") then
		local mobskin = inst.components.skinner.skin_name
		local getshiny = (mobskin ~= inst.prefab and mobskin ~= "") and string.gsub(mobskin, inst.prefab.."_", "" ) --will return false if no skin is equipped.
		if SKIN_RARITY_COLORS.ModMade ~= nil then
			if getshiny ~= false and inst.isshiny ~= 2 then
				inst.isshiny = getshiny --used for other purposes
				inst.AnimState:SetBuild("hound_ice_shiny_build_0"..inst.isshiny)
			end		
		end
	end	
end

local function setChar(inst)
	if not inst:HasTag("playerghost") then
    inst.AnimState:SetBank("hound")
    inst.AnimState:SetBuild("hound_ice")
    inst:SetStateGraph("SGhoundplayer")
	if inst.userid ~= nil and inst.userid == "KU_ppaqwYos" then
		inst.isshiny = 2
		SetSkinOverride(inst)
	end
	end
	
	if MONSTERHUNGER == "Disable" then
		inst.components.hunger:Pause()
	end
	if MOBPVPMODE == "Enable" then
		PvPTeleport(inst)
	end
	inst.components.sanity.ignore = true
end

local function DontTriggerCreep(inst)
    inst.components.locomotor.runspeed = (TUNING.HOUND_SPEED)
	inst.components.locomotor.fasteronroad = false
end

local function OnHitOther(inst, data)
	local other = data.target
	if other and other.components.freezable then
		other.components.freezable:AddColdness(0.5)
		--other.components.freezable:SpawnShatterFX()
	end
end

local function RemovePenalty(inst)
	inst.components.health:DeltaPenalty(-1.00) --Removes health penalty when reviving
	inst.components.health:DoDelta(20000, false) --Returns heals to max health upon reviving
end

local common_postinit = function(inst) 
	inst.soundsname = "wilson"

	inst.MiniMapEntity:SetIcon( "houndiceplayer.tex" )

	inst:DoTaskInTime(0, function()
  if ThePlayer then
      inst:EnableMovementPrediction(false)
   end
end)
end


local master_postinit = function(inst)
    inst.components.health:SetMaxHealth(150)
	inst.components.hunger:SetMax(100)
	inst.components.hunger:SetRate(0.2)
	--inst:AddComponent("healthRegenerate")
	inst.components.combat:SetRange(TUNING.WORM_ATTACK_DIST)
    inst.components.locomotor.runspeed = (TUNING.HOUND_SPEED)
	inst.components.locomotor.fasteronroad = false
	inst.components.combat.playerdamagepercent = MOBPVP
	inst.components.combat.pvp_damagemod = 1 --disables second pvp override.
	inst.components. combat:SetDefaultDamage(42)
	inst.components.combat:SetHurtSound("dontstarve/creatures/hound/hit")
    inst.components.temperature.inherentinsulation = -TUNING.INSULATION_SMALL
	inst.AnimState:SetBank("hound")
	inst.AnimState:SetBuild("hound_ice")	
	inst.OnSetSkin = function(skin_name)
    inst.AnimState:SetBuild("hound_ice")
	inst:SetStateGraph("SGhoundplayer")
	
	inst:ListenForEvent("ms_respawnedfromghost", DontTriggerCreep)
    DontTriggerCreep(inst)
	end
	inst:SetStateGraph("SGhoundplayer")
	inst.components.locomotor:SetShouldRun(true)
	inst.components.talker:IgnoreAll()
	if MONSTERHUNGER == "Disable" then
		inst.components.hunger:Pause()
	end
	inst.components.sanity.ignore = true
	
	inst:AddTag("hound")
	inst:AddTag("monster")
	--inst:AddTag("houndfriend")
	inst:AddTag("mobsleep")
	inst:AddTag("mobplayer")    
	inst:AddTag("character")
	
	inst.taunt = true
	inst.taunt2 = true
	inst.ghostbuild = "ghost_monster_build"
	inst.mobteleported = false
	inst.isshiny = 0
	
	inst.OnSave = OnSave
	inst.OnLoad = OnLoad	
	
	MakeCharacterPhysics(inst, 10, .5)
    inst.DynamicShadow:SetSize(2.5, 1.5)
    inst.Transform:SetFourFaced()
	
	inst:ListenForEvent("onhitother", OnHitOther)
	inst:ListenForEvent("attacked", OnAttacked)

	inst.components.eater:SetDiet({ FOODTYPE.MEAT }, { FOODTYPE.MEAT })
    inst.components.eater:SetCanEatHorrible()
	
	inst.components.eater:SetAbsorptionModifiers(1,1.50,1.50)

    inst.components.eater.strongstomach = true -- can eat monster meat!
	
	inst.components.temperature.mintemp = 20
    
    inst:AddComponent("lootdropper")
	inst.components.lootdropper:SetChanceLootTable('houndiceplayer')

    
	inst.freezable_extra_resist = 800
	
	MakeHugeFreezableCharacter(inst, "hound_body")
	--inst.components.freezable.onfreezefn = function()
        --inst.freezable_extra_resist = inst.freezable_extra_resist + 2
        --UpdateFreezeThreshold(inst)
    --end
	MakeMediumBurnableCharacter(inst, "hound_body")
    
	
	------------------
    
    ------------------

	
  	local light = inst.entity:AddLight()
  	inst.Light:Enable(true)
  	inst.Light:SetRadius(0)
  	inst.Light:SetFalloff(0.9)
  	inst.Light:SetIntensity(0.6)
  	inst.Light:SetColour(180/255,195/255,150/255)

  	--Stats varies day/night

	
	inst.components.talker.colour = Vector3(127/255, 0/255, 0/255)
	inst:ListenForEvent("respawnfromghost", RestoreNightvision)

    inst:DoTaskInTime(0, setChar)
	inst:DoTaskInTime(3, setSkin)
    inst:ListenForEvent("respawnfromghost", function()
		inst:DoTaskInTime(3, function()  inst.components.health:SetInvincible(false)
            if inst.components.playercontroller ~= nil then
				inst.components.playercontroller:EnableMapControls(true)
				inst.components.playercontroller:Enable(true)
			end
			inst.components.inventory:Show()
			inst:ShowActions(true)
            inst:ShowHUD(true)
            inst:SetCameraDistance()
			inst.sg:RemoveStateTag("busy")
            SerializeUserSession(inst) 
		end)
        inst:DoTaskInTime(5, setChar)
		inst:DoTaskInTime(5.1, setSkin)
		inst:DoTaskInTime(6, DontTriggerCreep)
		inst:DoTaskInTime(6, RemovePenalty)
		inst:DoTaskInTime(10, RestoreNightvision)
    end)
	
    return inst
	
end

if SKIN_RARITY_COLORS.ModMade ~= nil then
AddModCharacterSkin("houndiceplayer", 1, {normal_skin = "deerclops_shiny_build_01", ghost_skin = "ghost_monster_build"}, {"deerclops_shiny_build_01", "ghost_monster_build"}, {"DEERPLAYER", "FORMAL"})
end

return MakePlayerCharacter("houndiceplayer", prefabs, assets, common_postinit, master_postinit, start_inv)
