local MakePlayerCharacter = require "prefabs/player_common"

---------------------------
----------==Notes==--------
--
---------------------------

--Don't add assets unless absolutely needed.
local assets = 
{
	Asset("ANIM", "anim/krampus_hawaiian_basic.zip"),
    Asset("ANIM", "anim/krampus_hawaiian_build.zip"),
	Asset("ANIM", "anim/krampus_shiny_build_01.zip"),
	Asset("ANIM", "anim/krampus_shiny_build_02.zip"),
}
--Might be completely pointless here. I don't know.
local prefabs = 
{	

}	
--Note: Becareful when adding starting items.
--People are likely to spam changecharacter to get more of them.	
local start_inv = 
{
	--'prefab',
	--"spear",
}
-----------------------
--Stats--
--Not tested! Might cause issues!
--These should make editing easier.
local mob = 
{
	health = 300,
	hunger = 100,
	hungerrate = 0.10, --I think .25 is defualt.
	sanity = 100,
	runspeed = TUNING.KRAMPUS_SPEED,
	walkspeed = TUNING.KRAMPUS_SPEED,
	damage = 30*2,
	range = 2.3,
	bank = "krampus",
	build = "krampus_build",
	scale = 1,
	build2 = "krampus_hawaiian_build",
	--build3 = "beard_monster",
	stategraph = "SGkrampusp",
	minimap = "krampusp.tex",
	
}
-----------------------
--Loot that drops when you die, duh.
SetSharedLootTable('krampusp',
-----Prefab---------------------Chance------------
{
    {'monstermeat',  1.0},
    {'charcoal',     1.0},
    {'charcoal',     1.0},
    {'krampus_sack', .01},  
   
})

local function makebagfull(inst)
    inst.AnimState:Show("SACK")
    inst.AnimState:Hide("ARM")
end

local function makebagempty(inst)
    inst.AnimState:Hide("SACK")
    inst.AnimState:Show("ARM")
end

local function onattacked(inst, data) --YOU'VE BEEN MURDERED! RUN AWAY!
	local x, y, z = inst.Transform:GetWorldPosition()
    local ents = TheSim:FindEntities(x, y, z, 30, { "rabbit" }, { "INLIMBO" })
    local maxnum = 5
    for i, v in ipairs(ents) do
        v:PushEvent("gohome")
        if i >= maxnum then
            break
        end
    end
end

local function EquipHat(inst) --If a hat removes the head, this fixes that.
    local head = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD)
	if head then
		inst.AnimState:Show("HEAD")
	end 
end

local function Equip(inst)
    local hands = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS) or nil
	local head = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD) or nil
	local body = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.BODY) or nil
	if hands ~= nil and hands.components.weapon then
		hands.components.weapon:SetDamage(45*2)
        hands.components.weapon:SetRange(TUNING.BISHOP_ATTACK_DIST+2, TUNING.BISHOP_ATTACK_DIST+6)
        hands.components.weapon:SetProjectile("spider_web_spit")
	end
end

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

local function SetNightVision(inst, enable) --This should be obvious
    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 RestoreNightImmunity(inst) --Resets immunity to Grue

	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 onupdate(inst, dt)
    inst.charge_time = inst.charge_time - dt
    if inst.charge_time <= 0 then
        inst.charge_time = 0
		if inst.charge_task ~= nil then
            inst.charge_task:Cancel()
            inst.charge_task = nil
        end
        inst.specialatk = true
		inst.sg:GoToState("special_atk1")
    else
    --    
    end
end

local function OnLongUpdate(inst, dt)
    inst.charge_time = math.max(0, inst.charge_time - dt)
end

local function RandomSkinSet(inst)
	if inst.skinn ~= nil and inst.skinn == 1 then
		inst.AnimState:SetBuild(mob.build)
	elseif inst.skinn ~= nil and inst.skinn == 2 then
		inst.AnimState:SetBuild(mob.build2)
	end		
end	


local function StartTimer(inst, duration)
    inst.charge_time = duration
	inst.specialatk = false

    if inst.charge_task == nil then
        inst.charge_task = inst:DoPeriodicTask(1, onupdate, nil, 1)
        onupdate(inst, 0)
    end
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 and data.charge_time ~= nil then
        StartTimer(inst, data.charge_time)
		inst.skinn = data.skinn or 0
		RandomSkinSet(inst)
		inst.mobteleported = data.mobteleported or false
		inst.isshiny = data.isshiny or 0
    end
end

local function onsave(inst, data)
    data.charge_time = inst.charge_time > 0 and inst.charge_time or nil
	data.skinn = inst.skinn or 0
	data.mobteleported = inst.mobteleported or false
	data.isshiny = inst.isshiny or 0
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("krampus_shiny_build_0"..inst.isshiny)
			end		
		end
	end	
end

local function setChar(inst) --sets character when the player loads.
	if not inst:HasTag("playerghost") then
    inst.AnimState:SetBank(mob.bank)
    --inst.AnimState:SetBuild(mob.build)
	RandomSkinSet(inst)
    inst:SetStateGraph(mob.stategraph)
	end
	if MONSTERHUNGER == "Disable" then
	inst.components.hunger:Pause()
	end
	if MOBPVPMODE == "Enable" then
		PvPTeleport(inst)
	end
	inst.components.sanity.ignore = true
    inst.components.locomotor.runspeed = (mob.runspeed)
	inst.components.locomotor.walkspeed = (mob.walkspeed)
	inst.components.locomotor.fasteronroad = false
	
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(mob.minimap)
	--inst.AnimState:SetMultColour(1, 1, 1, 0.5)

	inst:DoTaskInTime(0, function() 
   if ThePlayer then
      ThePlayer:EnableMovementPrediction(false)
   end
end)
	--Night Vision that toggles, might be a better way to do this.
	--Enables at night, disables during the day.
	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 = (mob.runspeed)
	inst.components.locomotor.walkspeed = (mob.walkspeed)
end


local master_postinit = function(inst)
	------------------------------------------
	--Stats--
    inst.components.health:SetMaxHealth(mob.health)
	inst.components.hunger:SetMax(mob.hunger)
	inst.components.sanity:SetMax(mob.sanity)
	inst.components.hunger:SetRate(mob.hungerrate)
	------------------------------------------
	--Combat--
	--inst:AddComponent("healthSRegenerate")
	inst.components.combat.playerdamagepercent = MOBPVP
	--inst.components.combat:SetAttackPeriod(TUNING.WORM_ATTACK_PERIOD)
	inst.components.combat:SetRange(mob.range)
	inst.components.combat:SetDefaultDamage(mob.damage) --does double damage against mobs.
	--inst.components.combat:SetHurtSound("dontstarve_DLC001/creatures/vargr/hit")
	
    inst.components.temperature.inherentinsulation = -TUNING.INSULATION_SMALL
	inst.AnimState:SetBank(mob.bank)
	inst.AnimState:SetBuild(mob.build)
	
	inst.OnSetSkin = function(skin_name)
		inst.AnimState:SetBuild(mob.build)
		inst:SetStateGraph(mob.stategraph)
	
		inst:ListenForEvent("ms_respawnedfromghost", DontTriggerCreep)
		DontTriggerCreep(inst)	
	end
	inst:SetStateGraph(mob.stategraph)
	inst.components.talker:IgnoreAll()
	if MONSTERHUNGER == "Disable" then
		inst.components.hunger:Pause()
	end
	inst.components.sanity.ignore = true
	----------------------------------
	--Locomotor--
    inst.components.locomotor.runspeed = (mob.runspeed)
	inst.components.locomotor.walkspeed = (mob.walkspeed)
	inst.components.locomotor:SetSlowMultiplier( 1 )
    inst.components.locomotor:SetTriggersCreep(false)
    inst.components.locomotor.pathcaps = { ignorecreep = true }
	
	----------------------------------
	--Loot drops--
	inst:AddComponent("lootdropper")
    inst.components.lootdropper:SetChanceLootTable('krampusp')
	----------------------------------
	--Temperature and Weather Components--
	inst.components.temperature.maxtemp = 60 --prevents overheating
	inst.components.temperature.mintemp = 20 --prevents freezing
	--inst.components.moisture:SetInherentWaterproofness(1) --Prevents getting wet.
	----------------------------------
	--Tags--
	inst:RemoveTag("character") --This is removed to make certain mobs to not treat you like a player.
	inst:AddTag("hostile")
    inst:AddTag("scarytoprey")
    inst:AddTag("monster")
	inst:AddTag("special_atk2")
	
	inst.taunt = true
	inst.specialatk = true
	inst.isshiny = 0
	inst.skinn = 1
	inst.mobsleep = true
	inst.mobplayer = true
	inst.ghostbuild = "ghost_monster_build"
	inst.mobteleported = false
	MakeLargeBurnableCharacter(inst, "krampus_torso")
	----------------------------------
	--SanityAura--
	--inst:AddComponent("sanityaura")
	--inst.components.sanityaura.aurafn = CalcSanityAura
	
	----------------------------------
	--Eater--
	
	--Kinds of diets I know of: MEAT, ROUGHAGE(grass and stuff), GEARS, OMNI(no idea it prevents eating entirely, just disable this if you want both meat and veggies).
	--inst.components.eater:SetDiet({ FOODTYPE.VEGGIE }, { FOODTYPE.VEGGIE })
    inst.components.eater:SetAbsorptionModifiers(4,3,3) --This might multiply food stats.
	inst.components.eater:SetCanEatHorrible() --check to make them eat monster meat.
	inst.components.eater.strongstomach = true -- can eat monster meat!
	--inst.components.eater.eatwholestack = true --should eat the entire stack and get all the benefits.
	--inst.components.eater.ignoresspoilage = true -- Can eat spoiled food without consequence. Might keep food stats as if fresh.
    --inst.components.eater:SetCanEatGears() --self explanatory.
    --inst.components.eater:SetOnEatFn(OnEat) --Runs a function when the player eats something.
	---------------------------------
	--Physics and Scale--
	
	MakeCharacterPhysics(inst, 10, .5)
	--MakeGhostPhysics(inst, 1, .5) --Special physics for flying characters(?)
    inst.Transform:SetScale(mob.scale, mob.scale, mob.scale)
    inst.DynamicShadow:SetSize(3, 1)
	--inst.DynamicShadow:Enable(false) --Disables shadows.
    inst.Transform:SetFourFaced()
	inst.AnimState:Hide("ARM")
	---------------------------------
	--Shedder--
	
	--inst:AddComponent("shedder")
	--inst.components.shedder.shedItemPrefab = "spidergland"
	--inst.components.shedder.shedHeight = 0.1
	--inst.components.shedder:StartShedding(1200) --Note: 480 is 1 day. 480 x n = n amount of days.
	---------------------------------
	--Periodic Spawner--
	
	--inst:AddComponent("periodicspawner")
   -- inst.components.periodicspawner:SetPrefab("guano")
    --inst.components.periodicspawner:SetRandomTimes(120,240)
    --inst.components.periodicspawner:SetDensityInRange(30, 2)
    --inst.components.periodicspawner:SetMinimumSpacing(8)
    --inst.components.periodicspawner:Start()
	---------------------------------
	--Listeners--
	
	--inst:ListenForEvent("equip", EquipHat) --Shows head when hats make heads disappear.
	--inst:ListenForEvent("equip", Equip) --Enables spitting.
	--inst:ListenForEvent("attacked", onattacked)
	--inst:ListenForEvent("onhitother", OnHitOther)
	---------------------------------
	--Functions that saves and loads data.
	
    --inst.OnPreLoad = onpreload
	inst.OnLongUpdate = OnLongUpdate
	inst.OnSave = onsave
	inst.OnLoad = onload
	------------------------------------------------------
	
	inst:AddComponent("timer")
	
	inst.userfunctions =
    {
        StartTimer = StartTimer,
    }
	
	inst.charge_task = nil
    inst.charge_time = 0
	
    ------------------------------------------------------
	--Light and Character Functions. Don't Touch.--
    	
  	local light = inst.entity:AddLight() --Just added to make immune to grue. No visible or useful light.
  	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) --Text color when player Examines.
	inst:ListenForEvent("respawnfromghost", RestoreNightImmunity)

    inst:DoTaskInTime(0, setChar) --Sets Character.
	inst:DoTaskInTime(3, setSkin)
    inst:ListenForEvent("respawnfromghost", function() --Runs functions when character revives from Ghost.
		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) --Removes death penalties and restore health if wanted.
		inst:DoTaskInTime(6, DontTriggerCreep)-- Restores speed on revive.
		inst:DoTaskInTime(10, RestoreNightImmunity) --explains itself.
    end)
	
    return inst
	
end

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


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