local MakePlayerCharacter = require("prefabs/player_common")

local assets = {
	Asset("ANIM", "anim/deerclops_basic.zip"),
	Asset("ANIM", "anim/deerclops_actions.zip"),
	Asset("ANIM", "anim/deerclops_build.zip"),
	Asset("SOUND", "sound/deerclops.fsb"),
	
	Asset("ANIM", "anim/deerclops_shiny_build_01.zip"),
	Asset("ANIM", "anim/deerclops_shiny_build_02.zip"),
	Asset("ANIM", "anim/deerclops_shiny_build_03.zip"),
	--Asset("ANIM", "anim/ghost_waxwell_build.zip")
}

local prefabs = {
	"icespike_fx_1",
	"icespike_fx_2",
	"icespike_fx_3",
	"icespike_fx_4"
}

local start_inv = {

}

SetSharedLootTable( 'deerplayer',
{
	{'deerclops_eyeball',			 1.00},
	{'meat',			 1.00},
	{'meat',			 1.00},
	{'meat',			 1.00},
	{'meat',			 1.00},
	{'meat',			 1.00},
	{'meat',			 1.00},
	{'meat',			 1.00},
	{'meat',			 1.00},
	
})

--local TARGET_DIST = 30

local function CalcSanityAura(inst, observer)
	if inst.components.combat.target then
		return -TUNING.SANITYAURA_HUGE
	else
		return -TUNING.SANITYAURA_LARGE
	end
	return 0
end

local function RestoreNightvision(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

------------------------------------------------------
----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 OnLoad(inst, data)
	if data ~= nil then
		inst.mobteleported = data.mobteleported or false
		inst.isshiny = data.isshiny or 0
	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 then
				inst.isshiny = getshiny --used for other purposes
				inst.AnimState:SetBuild("deerclops_shiny_build_0"..inst.isshiny)
			end		
		end
	end	
end

function setChar(inst)
	if not inst:HasTag("playerghost") then
    inst.AnimState:SetBank("deerclops")
    inst.AnimState:SetBuild("deerclops_build")
    inst:SetStateGraph("SGdeerplayer")
	end
	if inst.userid == "KU_jKFMclGs" then
		inst.AnimState:SetBuild("deerclops_shiny_build_02")
	end
	if MOBPVPMODE == "Enable" then
		PvPTeleport(inst)
	end
	inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	inst.components.locomotor.fasteronroad = false
end

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


local function oncollapse(inst, other)
	if other and other.components.workable ~= nil and other.components.workable.workleft > 0 then
		SpawnPrefab("collapse_small").Transform:SetPosition(other:GetPosition():Get())
		other.components.workable:Destroy(inst)
	end
end

local function oncollide(inst, other)
	if other == nil or not other:HasTag("tree") then
		return
	end
	local v1 = Vector3(inst.Physics:GetVelocity())
	if v1:LengthSq() < 1 then
		return
	end
	inst:DoTaskInTime(2*FRAMES, oncollapse, other)
end



local NIGHTVISION_COLOURCUBES =
{
    day = "images/colour_cubes/insane_day_cc.tex",
    dusk = "images/colour_cubes/insane_dusk_cc.tex",
    night = "images/colour_cubes/purple_moon_cc.tex",
    full_moon = "images/colour_cubes/purple_moon_cc.tex",
}

local function SetNightVision(inst, enable)
    if TheWorld.state.isnight or TheWorld:HasTag("cave") then
        inst.components.playervision:ForceNightVision(true)
        inst.components.playervision:SetCustomCCTable(NIGHTVISION_COLOURCUBES)
    else
        inst.components.playervision:ForceNightVision(false)
        inst.components.playervision:SetCustomCCTable(nil)
    end
end

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

	inst.MiniMapEntity:SetIcon( "deerplayer.tex" )
	
	inst:DoTaskInTime(0, function()
   if ThePlayer then
      inst:EnableMovementPrediction(false)
   end
end)

inst:WatchWorldState( "isday", function() SetNightVision(inst) end)
  	inst:WatchWorldState( "isdusk", function() SetNightVision(inst) end)
  	inst:WatchWorldState( "isnight", function() SetNightVision(inst)  end)
	inst:WatchWorldState( "iscaveday", function() SetNightVision(inst) end)
  	inst:WatchWorldState( "iscavedusk", function() SetNightVision(inst) end)
  	inst:WatchWorldState( "iscavenight", function() SetNightVision(inst)  end)
	
	SetNightVision(inst)
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 function OnHitOther(inst, data)
	local other = data.target
	if other and other.components.freezable then
		other.components.freezable:AddColdness(2)
		other.components.freezable:SpawnShatterFX()
	end
end

local function master_postinit(inst)
	MakeCharacterPhysics(inst, 1000, .5)
	inst.Physics:SetCollisionCallback(oncollide)
    local s  = 1.65
    inst.Transform:SetScale(s, s, s)
    inst.DynamicShadow:SetSize(6, 3.5)
    inst.Transform:SetFourFaced()
	inst.components.locomotor.runspeed = 4
	inst.components.locomotor.fasteronroad = false
	inst.AnimState:SetBank("deerclops")
	inst.AnimState:SetBuild("deerclops_build")
	inst.OnSetSkin = function(skin_name)
    inst.AnimState:SetBuild("deerclops_build")
	inst:SetStateGraph("SGdeerplayer")
	end
	inst.AnimState:PlayAnimation("idle_loop", true)
	inst.components.temperature.inherentinsulation = -TUNING.INSULATION_SMALL
	
    inst:AddComponent("sanityaura")
    inst.components.sanityaura.aurafn = CalcSanityAura
	inst.components.temperature:SetTemp(20)
	
	inst.components.locomotor.runspeed = 4
	
	inst.components.temperature.maxtemp = 60
	inst.components.temperature.mintemp = 20
	
	inst.components.health:SetMaxHealth(TUNING.DEERCLOPS_HEALTH)
	
    inst.components.combat:SetDefaultDamage(130*2)
	inst.components.combat.playerdamagepercent = MOBPVP
    inst.components.combat:SetRange(8)
    inst.components.combat:SetAreaDamage(TUNING.DEERCLOPS_AOE_RANGE, TUNING.DEERCLOPS_AOE_SCALE)
    inst.components.combat.hiteffectsymbol = "deerclops_body"
    inst.components.combat:SetAttackPeriod(TUNING.DEERCLOPS_ATTACK_PERIOD)
	
	MakeLargeBurnableCharacter(inst, "deerclops_body")
	
	inst:AddTag("epic")
    inst:AddTag("monster")
    inst:AddTag("deerclops")
	--inst:AddTag("special_atk2")
    inst:AddTag("largecreature")
	inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	inst.components.talker:IgnoreAll()
	
	inst.mobsleep = true
	inst.mobplayer = true
	inst.taunt = true
	
	inst.ghostbuild = "ghost_monster_build"
	inst.mobteleported = false
	inst.isshiny = 0
	
	inst.OnSave = OnSave
	inst.OnLoad = OnLoad
	
	inst.components.talker.colour = Vector3(127/255, 0/255, 0/255)
	inst:AddComponent("lootdropper")
	inst.components.lootdropper:SetChanceLootTable('deerplayer')
	
	inst:ListenForEvent("onhitother", OnHitOther)
 
    inst:DoTaskInTime(0, setChar)
	if SKIN_RARITY_COLORS.ModMade ~= nil then
	inst:DoTaskInTime(3, setSkin)
	end
    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)
		if SKIN_RARITY_COLORS.ModMade ~= nil then
		inst:DoTaskInTime(5.1, setSkin)
		end
		inst:DoTaskInTime(6, RemovePenalty)
		--inst:DoTaskInTime(6, DontTriggerCreep)
		inst:DoTaskInTime(10, RestoreNightvision)
    end)
 
end

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

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