local MakePlayerCharacter = require "prefabs/player_common"

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

--Don't add assets unless absolutely needed.
local assets = 
{
	Asset("ANIM", "anim/spider_warrior_shiny_build_01.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",
}

local start_inv2 = {
	"spiderhome",
}

if MOBHOUSE == "Enable1" or MOBHOUSE == "Enable3" then
	start_inv = start_inv2
end
-----------------------
local mob = 
{
	health = 300,
	hunger = 150,
	hungerrate = 0.15, --I think .25 is defualt.
	sanity = 100,
	runspeed = 6,
	walkspeed = 6,
	damage = 40*2,
	range = TUNING.SPIDER_WARRIOR_MELEE_RANGE,
	bank = "spider",
	build = "spider_warrior_build",
	scale = 1,
	--build2 = "alternate build here",
	stategraph = "SGwarriorp",
	minimap = "warriorp.tex",
	
}
-----------------------
--Loot that drops when you die, duh.
SetSharedLootTable('warriorp',
-----Prefab---------------------Chance------------
{
    {'monstermeat',			1.00},
	{'spidergland',			1.00},
    
   
})

local function onattacked(inst, data) --Get friends to come help you out when you're in trouble!
    if data.attacker then
        inst.components.combat:SetTarget(data.attacker)
        inst.components.combat:ShareTarget(data.attacker, 40, function(dude) return dude:HasTag("spider") and not dude.components.health:IsDead() end, 10)
    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 onhitother2(inst, other)
    inst.components.combat:SetTarget(other)
    inst.components.combat:ShareTarget(other, 30, function(dude) return dude:HasTag("spider") and not dude.components.health:IsDead() end, 10)
end

local function OnHitOther(inst)
    local hands = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HANDS) or nil
	if hands ~= nil and hands.components.finiteuses then
		hands.components.finiteuses:SetPercent(1)
	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 function CalcSanityAura(inst, observer)
	if inst.components.combat.target or MOBPVPMODE == "Enable" then
		return -TUNING.SANITYAURA_MED
	end

	return 0
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 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("spider_warrior_shiny_build_0"..inst.isshiny)
			end		
		end
	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 setChar(inst) --sets character when the player loads.
	if not inst:HasTag("playerghost") then
    inst.AnimState:SetBank(mob.bank)
    inst.AnimState:SetBuild(mob.build)
    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
      inst: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) --This is here to make sure the NightVision is enabled when a player rejoins.
	
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('warriorp')
	----------------------------------
	--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.
	MakeMediumBurnableCharacter(inst, "body")
	----------------------------------
	--Tags--
	inst:RemoveTag("character") --This is removed to make certain mobs to not treat you like a player.
	--inst:AddTag("special_atk1") --allows taunting.
    inst:AddTag("monster") --PIGS HATE HIM!
	inst:AddTag("spiderwhisperer")
	inst:AddTag("spider_warrior")
	
	inst.components.combat.onhitotherfn = onhitother2
	
	inst.taunt = true
	inst.isshiny = 0
	inst.mobsleep = true
	inst.mobplayer = true
	inst.ghostbuild = "ghost_monster_build"
	inst.mobteleported = false
	----------------------------------
	--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.MEAT, FOODTYPE.MEAT }, { FOODTYPE.MEAT, FOODTYPE.MEAT }) 
    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(1.5, .5)
	--inst.DynamicShadow:Enable(false) --Disables shadows.
    inst.Transform:SetFourFaced()
	---------------------------------
	--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.OnLongUpdate = onlongupdate
    inst.OnSave = OnSave
	inst.OnLoad = OnLoad
    --inst.OnPreLoad = onpreload
	------------------------------------------------------
    ------------------------------------------------------
	--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) --Prevents mobs from getting stuck when reviving.
            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) --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("warriorp", 1, {normal_skin = "spider_warrior_shiny_build_01", ghost_skin = "ghost_monster_build"}, {"spider_warrior_shiny_build_01", "ghost_monster_build"}, {"WARRIORP", "FORMAL"})
end


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