local MakePlayerCharacter = require "prefabs/player_common"

local assets = 
{
	Asset("ANIM", "anim/leif_shiny_build_02.zip"),
	Asset("ANIM", "anim/leif_shiny_build_04.zip"),
}
local prefabs = {	
    }
local start_inv = {
	"pinecone",
	"pinecone",
	"pinecone",
	"pinecone",
	"pinecone",
	"pinecone",
	"pinecone",
	"pinecone",
	"pinecone",
	"pinecone",
}

SetSharedLootTable('treeplayer',
{
    {'livingwood',             1.00},
	{'livingwood',             1.00},
	{'livingwood',             1.00},
	{'livingwood',             1.00},
	{'livingwood',             1.00},
	{'livingwood',             1.00},
    {'monstermeat',             1.00},
	{'monstermeat',             1.00},
   
})

local function EquipHat(inst)
    local head = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD)
	if head then

	inst.AnimState:Show("HEAD")
        
		
	end 
	
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 function RandomSkinSet(inst)

	if inst.skinn == 400 then --is a contributor
		inst.AnimState:SetBuild("leif_shiny_build_04")
	end
	if inst.skinn ~= nil and inst.skinn == 0 then
		inst.skinn = math.random(1,100)
		if inst.skinn >= 70 then
			inst.AnimState:SetBuild("leif_lumpy_build")
		else
			inst.AnimState:SetBuild("leif_build")
		end	
	else
		if inst.skinn ~=nil and inst.skinn >= 70 then
			inst.AnimState:SetBuild("leif_lumpy_build")
		elseif inst.skinn ~= nil and inst.skinn <= 69 then
			inst.AnimState:SetBuild("leif_build")
		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("leif_shiny_build_0"..inst.isshiny)
			end		
		end
	end	
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 setChar(inst)
	if not inst:HasTag("playerghost") then
    inst.AnimState:SetBank("leif")
    --inst.AnimState:SetBuild("leif_build")
	RandomSkinSet(inst)
    inst:SetStateGraph("SGtreeplayer")
	end
	inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
    inst.components.locomotor.runspeed = 3
	inst.components.locomotor.fasteronroad = false
	if MOBPVPMODE == "Enable" then
		PvPTeleport(inst)
	end
	
end

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

local common_postinit = function(inst) 
	--inst.soundsname = "beefalo"

	inst.MiniMapEntity:SetIcon( "treeplayer.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 DontTriggerCreep(inst)
    inst.components.locomotor.runspeed = 2
	inst.components.locomotor.walkspeed = 2
end


local master_postinit = function(inst)
    inst.components.health:SetMaxHealth(2000 * 1.25)
	inst.components.hunger:SetMax(200)
	
	--inst:AddComponent("healthRegenerate")
	inst.components.combat.playerdamagepercent = MOBPVP
    --inst.components.combat:SetAttackPeriod(TUNING.TALLBIRD_ATTACKPERIOD)
	inst.components.combat:SetRange(2 * 1.25)
    inst.components.locomotor.runspeed = 2
	inst.components.locomotor.walkspeed = 2
	inst.components.combat:SetDefaultDamage(125*2)
	--inst.components.combat:SetHurtSound("dontstarve_DLC001/creatures/vargr/hit")
	--inst.components.temperature.hurtrate = 0
    inst.components.temperature.inherentinsulation = -TUNING.INSULATION_SMALL
	inst.AnimState:SetBank("leif")
	inst.AnimState:SetBuild("leif_build")	
	inst.OnSetSkin = function(skin_name)
    inst.AnimState:SetBuild("leif_build")
	inst:SetStateGraph("SGtreeplayer")
	
	inst:ListenForEvent("ms_respawnedfromghost", DontTriggerCreep)
    DontTriggerCreep(inst)
	
	
	end
	inst:SetStateGraph("SGtreeplayer")
	inst.components.locomotor:SetShouldRun(false)
	inst.components.talker:IgnoreAll()
	inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	
	inst:AddComponent("lootdropper")
    inst.components.lootdropper:SetChanceLootTable('treeplayer')
	
	inst.components.temperature.maxtemp = 60
	inst.components.temperature.mintemp = 20
	
	inst:RemoveTag("character")
	inst:AddTag("epic")
    inst:AddTag("monster")
    inst:AddTag("largecreature")
	
	
	
	MakeLargeBurnableCharacter(inst, "marker")
	
	inst.ghostbuild = "ghost_monster_build"
	inst.mobteleported = false
	inst.skinn = 0
	inst.mobsleep = true
	inst.mobplayer = true
	inst.poisonimmune = true
	inst.hit_recovery = 3
	--inst.components.eater:SetDiet({ FOODTYPE.MEAT, FOODTYPE.MEAT }, { FOODTYPE.MEAT, FOODTYPE.MEAT })
    --inst.components.eater:SetAbsorptionModifiers(4,1,1)
	
	 inst.AnimState:PlayAnimation("idle_loop", true)
	
	inst.components.eater:SetCanEatHorrible()
	
	inst.components.eater.strongstomach = true -- can eat monster meat!

	MakeCharacterPhysics(inst, 1000, .5)
	inst.Physics:SetMass(99999)
    inst.DynamicShadow:SetSize(4, 2)
    inst.Transform:SetFourFaced()
	inst.Transform:SetScale(1.25, 1.25, 1.25)
	inst:AddComponent("shedder")
	inst.components.shedder.shedItemPrefab = "pinecone"
	inst.components.shedder.shedHeight = 0.5
	inst.components.shedder:StartShedding(480)
	
	--inst:ListenForEvent("equip", EquipHat)
	inst.isshiny = 0
	
	------------------
    inst.OnSave = OnSave
    inst.OnLoad = OnLoad
    ------------------

	
  	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)
	
	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, RemovePenalty)
		inst:DoTaskInTime(6, DontTriggerCreep)
		inst:DoTaskInTime(10, RestoreNightvision)
    end)
	
    return inst
	
end


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

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