local MakePlayerCharacter = require "prefabs/player_common"

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

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

}

if MOBHOUSE == "Enable1" or MOBHOUSE == "Enable3" then
	start_inv = start_inv2
end
-----------------------
local mob = 
{
	health = 250,
	hunger = 150,
	hungerrate = 0.15, --I think .25 is defualt.
	sanity = 100,
	runspeed = 6,
	walkspeed = 6,
	damage = 75,
	range = TUNING.TENTACLE_ATTACK_DIST + 1,
	bank = "tentacle",
	build = "tentacle",
	scale = 1,
	--build2 = "alternate build here",
	stategraph = "SGtentaclep",
	minimap = "tentaclep.tex",
	
}
-----------------------
--Loot that drops when you die, duh.
SetSharedLootTable('tentaclep',
-----Prefab---------------------Chance------------
{
    {'monstermeat',			1.00},
	{'tentaclespots',			0.50},   
})

local function PvPAbillity(inst)
--
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 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("tentacle_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 function SetSandstormImmunity(inst)
	if TheWorld.state.issummer and not TheWorld:HasTag("cave") then
        inst.components.playervision:ForceGoggleVision(true)
    else
        inst.components.playervision:ForceGoggleVision(false)
    end
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.
	
	inst:WatchWorldState( "issummer", function() SetSandstormImmunity(inst) end) --makes immune to Sandstorm visual issues.
	
	SetSandstormImmunity(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.components.health:StartRegen(10, 4)
	inst.components.combat.playerdamagepercent = MOBPVP
	inst.components.combat.pvp_damagemod = 1 --disables second pvp override.
	inst.components.combat:SetAttackPeriod(TUNING.TENTACLE_ATTACK_PERIOD)
	inst.components.combat:SetAreaDamage(mob.range, 0.8)
	inst.components.combat:SetRange(mob.range)
	inst.components.combat:SetDefaultDamage(mob.damage) --does double damage against mobs.	
    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()
	inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	----------------------------------
	--Locomotor--
    inst.components.locomotor.runspeed = (mob.runspeed)
	inst.components.locomotor.walkspeed = (mob.walkspeed)
	inst.components.locomotor.fasteronroad = false
	----------------------------------
	--Loot drops--
	inst:AddComponent("lootdropper")
    inst.components.lootdropper:SetChanceLootTable('tentaclep')
	----------------------------------
	--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("monster")    
    inst:AddTag("wet")
	inst:AddTag("noplayerindicator")
	inst:AddTag("notarget")
	
	inst.wants_to_sleep = false
	inst.mobplayer = true
	inst.poisonimmune = true
	inst.taunt = true
	inst.ghostbuild = "ghost_monster_build"
	inst.mobteleported = false
	inst.specialatk2 = true
	inst.isshiny = 0
	----------------------------------
	--SanityAura--
	inst:AddComponent("sanityaura")
	inst.components.sanityaura.aura = -TUNING.SANITYAURA_MED
	----------------------------------
	--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.ROUGHAGE }, { FOODTYPE.VEGGIE, FOODTYPE.ROUGHAGE })
    inst.components.eater:SetAbsorptionModifiers(4,1,1)
	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, 0.25, 0.5)
	--MakeGhostPhysics(inst, 1, .5) --Special physics for flying characters(?)
	inst.Physics:SetMass(99999)
    inst.Transform:SetScale(mob.scale, mob.scale, mob.scale)
    inst.DynamicShadow:SetSize(1.5, .5)
	inst.DynamicShadow:Enable(false) --Disables shadows.
    inst.Transform:SetTwoFaced()
	---------------------------------
	--Listeners--
	
	inst:ListenForEvent("equip", EquipHat) --Shows head when hats make heads disappear.
	---------------------------------
	--Functions that saves and loads data.
	
    inst.OnSave = OnSave
	inst.OnLoad = OnLoad
	------------------------------------------------------
    ------------------------------------------------------
	--Light and Character Functions. Don't Touch.--
    
	inst.components.grue:AddImmunity() --lights are used for charging, this should've been used anyways.
  	inst.Light:Enable(false)
    inst.Light:SetRadius(.85)
    inst.Light:SetFalloff(0.5)
    inst.Light:SetIntensity(.75)
    inst.Light:SetColour(255 / 255, 255 / 255, 236 / 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)
		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("tentaclep", 1, {normal_skin = "deerclops_shiny_build_01", ghost_skin = "ghost_monster_build"}, {"deerclops_shiny_build_01", "ghost_monster_build"}, {"DEERPLAYER", "FORMAL"})
end

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