local MakePlayerCharacter = require "prefabs/player_common"

local assets = {
	Asset("ANIM", "anim/knight_shiny_build_01.zip"),
	Asset("ANIM", "anim/knight_nightmare_shiny_build_01.zip"),
    --Asset("ANIM", "anim/knight_nightmare.zip"),
}

local prefabs =
{
    "gears",
}

local prefabs_nightmare =
{
    "gears",
    "thulecite_pieces",
    "nightmarefuel",
}

local start_inv = {
	--"hammer",
}

SetSharedLootTable( 'clockwork1player',
{
    {'gears',             1.00},
    {'gears',             1.00},
})

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

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

 local function SetBuild(inst)
 if not inst:HasTag("playerghost") then
    if inst.kind == "_nightmare" then
		inst.AnimState:SetBuild("knight_nightmare")
	else
		inst.AnimState:SetBuild("knight_build")
	end	
  end
 end
 
 local function EquipHat(inst) --If a hat removes the head, this fixes that.
    local head = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD) or nil
	if head ~= nil then
		inst.AnimState:Show("HEAD")
	end 
end
 
local function OnEat(inst)
	--local currentskin = inst.CurrentModdedSkin or "none"
    if inst.kind == "_nightmare" then
		if inst.isshiny == 0 then
		inst.AnimState:SetBuild("knight_build")
		inst.kind = ""
		else
		inst.AnimState:SetBuild("knight_shiny_build_0"..inst.isshiny)
		inst.kind = ""
		--elseif inst.isshiny > 2 and currentskin ~= "none" then
		--inst.AnimState:SetBuild("clockwork1player_shiny_build_"..currentskin)
		end
	else
		if inst.isshiny == 0 then
		inst.AnimState:SetBuild("knight_nightmare")
		inst.kind = "_nightmare"
		elseif inst.isshiny ~= 0 then
		inst.AnimState:SetBuild("knight_nightmare_shiny_build_0"..inst.isshiny)
		inst.kind = "_nightmare"
		--elseif inst.isshiny > 2 and currentskin ~= "none" then
		--inst.AnimState:SetBuild("clockwork1player_shiny_build_"..currentskin.."_alt")
		end
	end	
end

local function OnAttacked(inst, data)
        inst.components.combat:SetTarget(data.attacker)
        inst.components.combat:ShareTarget(data.attacker, 30, CanShareTarget, 5)
 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.kind = data.kind or ""
		SetBuild(inst)
		inst.mobteleported = data.mobteleported or false
	end
end

local function OnSave(inst, data)
	data.kind = inst.kind or ""
	data.mobteleported = inst.mobteleported or false
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
				if inst.kind and inst.kind == "" then
				inst.AnimState:SetBuild("knight_shiny_build_0"..inst.isshiny)
				else
				inst.AnimState:SetBuild("knight_nightmare_shiny_build_0"..inst.isshiny)
				end
			end		
		end
	end	
end
 
local NIGHTVISION_COLOURCUBES =
{
    day = "images/colour_cubes/mole_vision_off_cc.tex",
    dusk = "images/colour_cubes/mole_vision_on_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 setChar(inst)
	if inst.kind == "" then
	if not inst:HasTag("playerghost") then
	inst.AnimState:SetBank("knight")
    inst.AnimState:SetBuild("knight_build")
    inst:SetStateGraph("SGclockwork1player")
	end
	inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	else
	---
	if not inst:HasTag("playerghost") then
	inst.AnimState:SetBank("knight")
    inst.AnimState:SetBuild("knight_nightmare")
    inst:SetStateGraph("SGclockwork1player")
	end
	inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	end
	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 heals to max health upon reviving
end

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

	inst.MiniMapEntity:SetIcon( "clockwork1player.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.walkspeed = 8
	inst.components.locomotor.runspeed = 8
	inst.components.locomotor.fasteronroad = false
end

local master_postinit = function(inst)
    inst.components.health:SetMaxHealth(450)
	--inst:AddComponent("healthRegenerate")
    inst.components.temperature.inherentinsulation = -TUNING.INSULATION_SMALL
	inst.AnimState:SetBuild("knight_build")
	inst.OnSetSkin = function(skin_name)
    inst.AnimState:SetBuild("knight_build")
	inst:SetStateGraph("SGclockwork1player")
	end
	inst.AnimState:SetBank("knight")
	inst:SetStateGraph("SGclockwork1player")
	inst.components.talker:IgnoreAll()
	inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	--inst.components.temperature:SetTemp(20)
	
  	local light = inst.entity:AddLight()
  	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)
	
	SetNightVision(inst, true)
	inst.isshiny = 0
	
	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, DontTriggerCreep)
		inst:DoTaskInTime(6, RemovePenalty)
        inst:DoTaskInTime(6, setChar)
		inst:DoTaskInTime(6.1, setSkin)
		inst:DoTaskInTime(6, RestoreNightvision)
    end)
	
	--inst.components.eater:SetDiet({ FOODTYPE.GEARS }, { FOODTYPE.GEARS })
    inst.components.eater:SetCanEatHorrible()
	
	inst.components.temperature.maxtemp = 60
	inst.components.temperature.mintemp = 20

	MakeCharacterPhysics(inst, 50, .5)

    inst.DynamicShadow:SetSize(1.5, .75)
    inst.Transform:SetFourFaced()

	inst.kind = ""
	inst.ghostbuild = "ghost_monster_build"
	inst.mobteleported = false
	
	
	inst.components.locomotor.walkspeed = 8
	inst.components.locomotor.runspeed = 8
	inst.components.locomotor.fasteronroad = false
	
	MakeMediumBurnableCharacter(inst, "spring")
	
	inst.components.combat:SetDefaultDamage(30*2)
	inst.components.combat.playerdamagepercent = MOBPVP
	inst.components.combat:SetRange(2.5)
	inst.components.combat.hiteffectsymbol = "spring"
	
	inst.components.eater:SetOnEatFn(OnEat)
	
    inst:AddTag("monster")
    inst:AddTag("chess")
    inst:AddTag("knight")
	
	inst.taunt = true
	inst.mobplayer = true
	inst.mobsleep = true
	inst.poisonimmune = true

    inst:AddComponent("lootdropper")
    inst.components.lootdropper:SetChanceLootTable('clockwork1player')
	
	--inst.components.eater.eatwholestack = true
	
	inst.OnSave = OnSave
	inst.OnLoad = OnLoad
	
	inst:ListenForEvent("attacked", OnAttacked)
	inst:ListenForEvent("equip", EquipHat)


	
    return inst
	
end

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

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