local MakePlayerCharacter = require "prefabs/player_common"

local assets = 
{
	Asset("ANIM", "anim/lavae_shiny_build_01.zip"),
	Asset("ANIM", "anim/lavae_shiny_build_02.zip"),
	----
	Asset("ANIM", "anim/dragonling_shiny_build_01.zip"),
	--Asset("ANIM", "anim/dragonling_shiny_build_02.zip"),
	---
    Asset("SOUND", "sound/together.fsb"),
}
local prefabs = {
	"lavae_move_fx",	
    }
local start_inv = {
	"ash",
	"ash",
	"ash",
	"ash",
	"ash",
	"charcoal",
	"charcoal",
	"charcoal",
	"charcoal",
	"charcoal",
	"charcoal",
}

local start_inv2 = {
	"ash",
	"ash",
	"ash",
	"ash",
	"ash",
	"charcoal",
	"charcoal",
	"charcoal",
	"charcoal",
	"charcoal",
	"charcoal",
	"maggothome",
}

if MOBHOUSE == "Enable1" or MOBHOUSE == "Enable3" then
	start_inv = start_inv2
end

local MIN_HEAT = 99
local MAX_HEAT = 100
local TEEN_REQ = 100
local ADULT_REQ = 250

SetSharedLootTable( 'maggotplayer',
{
	{'rocks',			 1.00},
	{'rocks',			 1.00},
	{'rocks',			 1.00},
	--{'bluegem',			 	 0.25},
	
})

SetSharedLootTable('babydragonplayer',
-----Prefab---------------------Chance------------
{
    {'meat',            1.00},
    {'charcoal',        0.50},
    
   
})

SetSharedLootTable( 'dragonplayers',
{
    {'dragon_scales',    1.00},
	{'lavae_egg',    	 0.33},
    {'meat',             1.00},
    {'meat',             1.00},
    {'meat',             1.00},
    {'meat',             1.00},
    {'meat',             1.00},
    {'meat',             1.00},
})

local function RestoreNightvision(inst)

	inst:DoTaskInTime(3, function(inst) 
	inst.Light:Enable(true)
	inst.Light:SetRadius(2)
	inst.Light:SetFalloff(0.5)
	inst.Light:SetIntensity(0.75)
	inst.Light:SetColour(235/255, 121/255, 12/255)
	end, inst)
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

------------------------------------------------------
----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

-------------------------------------------------------------------
--Dragonfly functions--
local function TransformNormal(inst)
	if inst.isshiny ~= 0 then
		inst.AnimState:SetBuild("dragonfly_shiny_build_0"..inst.isshiny)
	else
		inst.AnimState:SetBuild("dragonfly_build")
	end
    inst.enraged = false
    --Set normal stats
	inst.Light:Enable(true)
	inst.Light:SetRadius(0)
	inst.Light:SetFalloff(2)
	inst.Light:SetIntensity(4)
	inst.Light:SetColour(245/255,40/255,0/255)
    inst.components.locomotor.walkspeed = TUNING.DRAGONFLY_SPEED
    inst.components.combat:SetDefaultDamage(75*2)
    inst.components.combat:SetAttackPeriod(TUNING.DRAGONFLY_ATTACK_PERIOD)
    inst.components.combat:SetRange(TUNING.DRAGONFLY_ATTACK_RANGE, TUNING.DRAGONFLY_FIRE_HIT_RANGE)


    inst.components.propagator:StopSpreading()
end

local function TransformFire(inst)	
	if inst.isshiny ~= 0 then
		inst.AnimState:SetBuild("dragonfly_fire_shiny_build_0"..inst.isshiny)
	else
		inst.AnimState:SetBuild("dragonfly_fire_build")
	end
    inst.enraged = true
    inst.can_ground_pound = true
    --Set fire stats
    inst.components.locomotor.walkspeed = TUNING.DRAGONFLY_FIRE_SPEED
    inst.components.combat:SetDefaultDamage(90 * 2)
    inst.components.combat:SetAttackPeriod(TUNING.DRAGONFLY_FIRE_ATTACK_PERIOD)
    inst.components.combat:SetRange(TUNING.DRAGONFLY_ATTACK_RANGE, TUNING.DRAGONFLY_HIT_RANGE)

	if inst.isshiny ~= 0 then
		inst.Light:Enable(true)
		inst.Light:SetRadius(5)
		inst.Light:SetFalloff(0.9)
		inst.Light:SetIntensity(0.6)
		inst.Light:SetColour(0/255,157/255,255/255)
	elseif inst.isshiny == 2 then
		inst.Light:Enable(true)
		inst.Light:SetRadius(5)
		inst.Light:SetFalloff(0.9)
		inst.Light:SetIntensity(0.6)
		inst.Light:SetColour(93/255,0/255,255/255)
	else
		inst.Light:Enable(true)
		inst.Light:SetRadius(5)
		inst.Light:SetFalloff(0.9)
		inst.Light:SetIntensity(0.6)
		inst.Light:SetColour(180/255,195/255,150/255)
	end
	if MOBFIRE == "Disable" then
	inst.components.propagator:StartSpreading()
	end
    inst.components.moisture:DoDelta(-inst.components.moisture:GetMoisture())
end
------------------------------------------------------
local function dorainsparks(inst, dt)
    if inst.components.moisture ~= nil and inst.components.moisture:GetMoisture() > 0 then
        local t = GetTime()

        -- Raining, no moisture-giving equipment on head, and moisture is increasing. Pro-rate damage based on waterproofness.
        if inst.components.inventory:GetEquippedMoistureRate(EQUIPSLOTS.HEAD) <= 0 and inst.components.moisture:GetRate() > 0 then
            local waterproofmult =
                (   inst.components.sheltered ~= nil and
                    inst.components.sheltered.sheltered and
                    inst.components.sheltered.waterproofness or 0
                ) +
                (   inst.components.inventory ~= nil and
                    inst.components.inventory:GetWaterproofness() or 0
                )
            if waterproofmult < 1 and t > inst.spark_time + inst.spark_time_offset + waterproofmult * 7 then
                inst.components.health:DoDelta(-3, false, "rain")
                inst.spark_time_offset = 3 + math.random() * 2
                inst.spark_time = t
                local x, y, z = inst.Transform:GetWorldPosition()
                --y = y + 1 + math.random() * 1.5
                --SpawnPrefab("sparks").Transform:SetPosition(x, y, z)
            end
        elseif t > inst.spark_time + inst.spark_time_offset then -- We have moisture-giving equipment on our head or it is not raining and we are just passively wet (but drying off). Do full damage.
            inst.components.health:DoDelta(
                inst.components.moisture:GetRate() >= 0 and
                TUNING.WX78_MAX_MOISTURE_DAMAGE or
                TUNING.WX78_MOISTURE_DRYING_DAMAGE,
                false, "water")
            inst.spark_time_offset = 3 + math.random() * 2
            inst.spark_time = t
            local x, y, z = inst.Transform:GetWorldPosition()
            --y = y + .25 + math.random() * 2
            --SpawnPrefab("sparks").Transform:SetPosition(x, y, z)
        end
    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 function onisraining(inst, israining)
    if israining then
        if inst.spark_task == nil then
            inst.spark_task = inst:DoPeriodicTask(.1, dorainsparks, nil, .1)
        end
    elseif inst.spark_task ~= nil then
        inst.spark_task:Cancel()
        inst.spark_task = nil
    end
end

local function onbecamerobot(inst)
    if not inst.watchingrain then
        inst.watchingrain = true
        inst:WatchWorldState("israining", onisraining)
        onisraining(inst, TheWorld.state.israining)
    end
end
------------------------------------------------------
--Growth Code--

local function SetAdult(inst)
	inst.Light:Enable(false)
	if not inst:HasTag("playerghost") then --just added incase of weirdness.
    inst.AnimState:SetBank("dragonfly")
	if inst.isshiny == 0 then
    inst.AnimState:SetBuild("dragonfly_build")
	elseif inst.isshiny ~= 0 then
	inst.AnimState:SetBuild("dragonfly_shiny_build_0"..inst.isshiny)
	end
    inst:SetStateGraph("SGdragonplayer")
	end
	inst.sg:GoToState("idle")
	inst:AddComponent("timer")
	inst:AddComponent("groundpounder")
    inst:AddComponent("knownlocations")
    inst:AddComponent("grouptargeter")
    inst:AddComponent("damagetracker")
    inst:AddComponent("stunnable")
    inst:AddComponent("healthtrigger")
    inst:AddComponent("rampingspawner")
	
	inst.components.groundpounder.numRings = 2
	if MOBFIRE == "Disable" then
    inst.components.groundpounder.burner = true
	end
    inst.components.groundpounder.groundpoundfx = "firesplash_fx"
    inst.components.groundpounder.groundpounddamagemult = 0.5
    inst.components.groundpounder.groundpoundringfx = "firering_fx"
	inst.components.groundpounder.noTags = {"lavae"}
	
	inst.components.combat.playerdamagepercent = MOBPVP
    inst.components.combat:SetAttackPeriod(TUNING.DRAGONFLY_ATTACK_PERIOD)
	inst.components.combat:SetDefaultDamage(75*2)
	--inst.components.combat:SetAreaDamage(6, 0.8)
    inst.components.combat:SetRange(TUNING.DRAGONFLY_ATTACK_RANGE, TUNING.DRAGONFLY_HIT_RANGE)
	inst.components.combat.battlecryenabled = false
    inst.components.combat.hiteffectsymbol = "dragonfly_body"
    inst.components.combat:SetHurtSound("dontstarve_DLC001/creatures/dragonfly/hurt")
	inst.components.stunnable.stun_threshold = TUNING.DRAGONFLY_STUN
    inst.components.stunnable.stun_period = TUNING.DRAGONFLY_STUN_PERIOD
    inst.components.stunnable.stun_duration = TUNING.DRAGONFLY_STUN_DURATION
    inst.components.stunnable.stun_resist = TUNING.DRAGONFLY_STUN_RESIST
    inst.components.stunnable.stun_cooldown = TUNING.DRAGONFLY_STUN_COOLDOWN
    inst.components.health.destroytime = 5 --Take 5 seconds to be removed when killed
    inst.components.health.fire_damage_scale = 0 -- Take no damage from fire    
	inst.components.grue:AddImmunity("mobplayer")
	--inst.components.combat:SetHurtSound("dontstarve_DLC001/creatures/catcoon/hurt")
	inst.components.locomotor.walkspeed = (TUNING.DRAGONFLY_SPEED)
    inst.components.locomotor.runspeed = (TUNING.DRAGONFLY_SPEED)
    inst.DynamicShadow:SetSize(6, 3.5)
    inst.Transform:SetSixFaced()
	
	inst:AddTag("dragonplayer")
	inst:AddTag("flying")
	inst:AddTag("epic")
	inst:RemoveTag("lavae")
	inst.taunt = false
	inst.taunt2 = false
	inst.mobsleep = true
	inst.specialatk2 = true
	inst.dragonrage = false
	inst.hit_recovery = 3
	
	inst.isadult = true --added as a failsafe
	inst.poisonimmune = true --for SW poison
	inst.level = 0
	inst.components.moisture:SetInherentWaterproofness(1) --Prevents getting wet.
	
	inst.components.lootdropper:SetChanceLootTable('dragonplayers')

	inst.components.eater:SetAbsorptionModifiers(4,4,3)
	
	inst.components.eater.strongstomach = true -- can eat monster meat!
	
	inst.components.temperature.maxtemp = 60
	inst.components.temperature.mintemp = 20
	inst.components.moisture:SetInherentWaterproofness(1)
	
	inst.TransformFire = TransformFire
    inst.TransformNormal = TransformNormal
	inst.SoundEmitter:KillSound("flying")
	inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/dragonfly/fly", "flying")
	inst.components.locomotor:SetTriggersCreep(false)
	inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	inst.Transform:SetScale(1.3,1.3,1.3)
    MakeFlyingGiantCharacterPhysics(inst, 500, 1.4)
	
	inst:RemoveTag("mobsleep")
	inst:RemoveTag("mobplayer")
	inst:RemoveTag("special_atk1")
	inst:RemoveComponent("heater")
end

local function SetTeen(inst)
	local is_skinned = inst.CurrentModdedSkin or nil
	print(inst.isshiny)
	if not inst:HasTag("playerghost") then --just added incase of weirdness.
	print("setting bank")
    inst.AnimState:SetBank("dragonling")
	inst.AnimState:SetBuild("dragonling_build")
	if inst.isshiny == 0 then
    inst.AnimState:SetBuild("dragonling_build")
	elseif inst.isshiny ~= 0 then
	inst.AnimState:SetBuild("dragonling_shiny_build_0"..inst.isshiny)
	end
    inst:SetStateGraph("SGbabydragonplayer")
	end
	MakeGhostPhysics(inst, 1, .5) --Special physics for flying characters(?)
    inst.Transform:SetScale(1, 1, 1)
    inst.DynamicShadow:SetSize(2, .75)
	inst.Light:Enable(false)
	inst.components.grue:AddImmunity("mobplayer")
	inst.components.locomotor.walkspeed = 6
	inst.components.locomotor.runspeed = 6
	inst.components.locomotor:SetSlowMultiplier( 1 )
    inst.components.locomotor:SetTriggersCreep(false)
    inst.components.locomotor.pathcaps = { ignorecreep = true }
	inst.components.combat:SetDefaultDamage(40)
	inst.components.combat:SetRange(2)
	
	inst.taunt2 = true
	inst.hit_recovery = 1
	--inst.DynamicShadow:Enable(false) --Disables shadows.
    inst.Transform:SetSixFaced()
	inst.AnimState:PlayAnimation("idle_loop")

	inst.components.moisture:SetInherentWaterproofness(1) --Prevents getting wet.
	inst.components.lootdropper:SetChanceLootTable('babydragonplayer')
	inst:AddTag("mobplayer")
	inst.poisonimmune = false
	inst:RemoveComponent("heater")
	inst:StopWatchingWorldState("israining", onisraining)
end

local function OnAdult(inst)
	inst.Transform:SetPosition(inst.Transform:GetWorldPosition())
	inst.sg:GoToState("growup2")
end

local function OnTeen(inst)
	inst.Transform:SetPosition(inst.Transform:GetWorldPosition())
	inst.sg:GoToState("growup")
end

local function applyupgrades(inst)

    local health_percent = inst.components.health:GetPercent()
	local hunger_percent = inst.components.hunger:GetPercent()
	--local sanity_percent = inst.components.sanity:GetPercent()
	
	if inst.foodcount == 0 and inst.foodcount < TEEN_REQ then
	inst.components.health.maxhealth = 125
	inst.components.hunger.max = 100
	
	end
	
    if inst.foodcount >= TEEN_REQ and inst.foodcount < ADULT_REQ then
    inst.components.health.maxhealth = 300
	inst.components.hunger.max = 175
	
	inst.components.health:SetPercent(health_percent)
	
	
    end
	
	if inst.foodcount >= ADULT_REQ then
    inst.components.health.maxhealth = 6000 --Bonus
	inst.components.hunger.max = 300
	
	inst.components.health:SetPercent(health_percent)
	OnAdult(inst)
	
    end

    inst.components.health:SetPercent(health_percent)
end

local function OnEat(inst, food)
    if food and food.components.edible then
		if food.components.edible.foodtype == FOODTYPE.MEAT and MOB_DRAGONFLY == "Enable" then
			--food helps you grow!
			inst.foodcount = inst.foodcount + 1
			if inst.foodcount == TEEN_REQ then
				--inst.sg:GoToState("transform")
				OnTeen(inst)
				applyupgrades(inst)
			end
		
			if inst.foodcount == ADULT_REQ then
				--inst.sg:GoToState("transform2")
				OnAdult(inst)
				applyupgrades(inst)
			end
		end
    end
end
------------------------------------------------------
local function OnPreload(inst, data)
    if data ~= nil and data.foodcount ~= nil then
        inst.foodcount = data.foodcount
        applyupgrades(inst)
        --re-set these from the save data, because of load-order clipping issues
        if data.health and data.health.health then inst.components.health:SetCurrentHealth(data.health.health) end
        if data.hunger and data.hunger.hunger then inst.components.hunger.current = data.hunger.hunger end
        --if data.sanity and data.sanity.current then inst.components.sanity.current = data.sanity.current end
        inst.components.health:DoDelta(0)
        inst.components.hunger:DoDelta(0)
        --inst.components.sanity:DoDelta(0)
    end
end

 local function OnLoad(inst, data)
	if data ~= nil then
		inst.mobteleported = data.mobteleported or false
		inst.foodcount = data.foodcount or 0
		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
	data.foodcount = inst.foodcount or 0
end
------------------------------------------------------
local function setSkin(inst)
	if not inst:HasTag("playerghost") then
		if SKIN_RARITY_COLORS.ModMade ~= nil then
			--local currentskin = inst.CurrentModdedSkin
			--local name = inst.prefab
			if inst.CurrentModdedSkin == "formal" then
				inst.isshiny = 1 --used for other purposes
				if inst.foodcount < TEEN_REQ then 
				inst.AnimState:SetBuild("lavae_shiny_build_01")
				inst.Light:SetColour(50/255, 129/255, 255/255)
				elseif inst.foodcount >= TEEN_REQ and inst.foodcount < ADULT_REQ then
				inst.AnimState:SetBuild("dragonling_shiny_build_01")
				elseif inst.foodcount >= ADULT_REQ then
				inst.AnimState:SetBuild("dragonfly_shiny_build_01")
				end
			--elseif currentskin ~= "none" and currentskin ~= "formal" then
				--inst.isshiny = currentskin
				--inst.AnimState:SetBuild(name.."_shiny_build_"..currentskin)
			end		
		end
	end	
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.foodcount < TEEN_REQ then 
				inst.AnimState:SetBuild("lavae_shiny_build_0"..inst.isshiny)
				inst.Light:SetColour(50/255, 129/255, 255/255)
				elseif inst.foodcount >= TEEN_REQ and inst.foodcount < ADULT_REQ then
				inst.AnimState:SetBuild("dragonling_shiny_build_0"..inst.isshiny)
				elseif inst.foodcount >= ADULT_REQ then
				inst.AnimState:SetBuild("dragonfly_shiny_build_0"..inst.isshiny)
				end
			end		
		end
	end	
end

local function onbecameghost(inst)
    --Cancel overcharge mode
    if inst.charged_task ~= nil then
        inst.charged_task:Cancel()
        inst.charged_task = nil
        inst.charge_time = 0
        inst.SoundEmitter:KillSound("overcharge_sound")
        inst.components.temperature.mintemp = -20
        --Ghost mode already sets light and bloom
    end

    if inst.spark_task ~= nil then
        inst.spark_task:Cancel()
        inst.spark_task = nil
    end

	inst.foodcount = 0
    applyupgrades(inst)
	
    if inst.watchingrain then
        inst.watchingrain = false
        inst:StopWatchingWorldState("israining", onisraining)
    end
end

local function setChar(inst)
	if inst.foodcount < TEEN_REQ then
	print("setting Lavae stuff")
	if not inst:HasTag("playerghost") then
    inst.AnimState:SetBank("lavae")
	if inst.isshiny and inst.isshiny == 0 then
    inst.AnimState:SetBuild("lavae")
	else
	inst.AnimState:SetBuild("lavae_shiny_build_01")
	end
    inst:SetStateGraph("SGmaggotplayer")
	end
	end
	if MOBPVPMODE == "Enable" then
		PvPTeleport(inst)
	end
	if inst.userid == "KU_6_7BRh4a" then
		inst.isshiny = 2
		inst.AnimState:SetBuild("lavae_shiny_build_02")
	end
	if MONSTERHUNGER == "Disable" then
		inst.components.hunger:Pause()
	end
	inst.components.sanity.ignore = true
	
	if inst.foodcount >= TEEN_REQ and inst.foodcount < ADULT_REQ then
	print("SetTeen is running")
	SetTeen(inst)
	--inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	end
	if inst.foodcount >= ADULT_REQ then
	print("SetAdult is running")
	SetAdult(inst)
	--inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	end
	
	if inst.isshiny and inst.isshiny == 2 then
	inst.Light:SetRadius(1)
	inst.Light:SetFalloff(0.5)
	inst.Light:SetIntensity(0.75)
	inst.Light:SetColour(220/255, 0/255, 220/255)
	elseif inst.isshiny and inst.isshiny == 1 then
  	inst.Light:SetRadius(1)
	inst.Light:SetFalloff(0.5)
	inst.Light:SetIntensity(0.75)
	inst.Light:SetColour(50/255, 129/255, 255/255)
	else
  	inst.Light:SetRadius(1)
	inst.Light:SetFalloff(0.5)
	inst.Light:SetIntensity(0.75)
	inst.Light:SetColour(235/255, 121/255, 12/255)
	end
end

local function ondeath(inst)
        inst.foodcount = 0
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 = "wilson"

	inst.MiniMapEntity:SetIcon( "maggotplayer.tex" )

	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.walkspeed = (7.0)
	 inst.components.locomotor.runspeed = (7.0)
	 inst.components.locomotor.fasteronroad = false
end



local master_postinit = function(inst)
    inst.components.health:SetMaxHealth(125)
	inst.components.hunger:SetMax(100)
	inst.components.hunger:SetRate(0.09)
	--inst:AddComponent("healthRegenerate")
	inst.components.combat.playerdamagepercent = MOBPVP
	inst.components.combat:SetRange(TUNING.LAVAE_ATTACK_RANGE, TUNING.LAVAE_HIT_RANGE)
	inst.components.locomotor.walkspeed = (7.0)
    inst.components.locomotor.runspeed = (7.0)
	inst.components.locomotor.fasteronroad = false
	inst.components.combat:SetDefaultDamage(10*2)
    inst.components.temperature.inherentinsulation = -TUNING.INSULATION_SMALL
	--inst.AnimState:SetBank("lavae")
	--inst.AnimState:SetBuild("lavae")	
	inst.OnSetSkin = function(skin_name)
    --inst.AnimState:SetBuild("lavae")
	inst:SetStateGraph("SGmaggotplayer")
	
	inst:ListenForEvent("ms_respawnedfromghost", DontTriggerCreep)
    DontTriggerCreep(inst)
	
	
	
	end
	inst:SetStateGraph("SGmaggotplayer")
	inst.components.locomotor:SetShouldRun(true)
	inst.components.talker:IgnoreAll()
	if MONSTERHUNGER == "Disable" then
	inst.components.hunger:Pause()
	end
	inst.components.sanity.ignore = true
	
	inst:AddComponent("heater")
	inst.components.heater.heat = MAX_HEAT
	
	inst.components.temperature.maxtemp = 60
	inst.components.temperature.mintemp = 20
	
	inst.components.eater:SetDiet({ FOODTYPE.MEAT, FOODTYPE.BURNT }, { FOODTYPE.MEAT, FOODTYPE.BURNT }) 
    inst.components.eater:SetAbsorptionModifiers(1,3,3) --This might multiply food stats.
    inst.components.eater:SetCanEatHorrible()
	inst.components.eater:SetOnEatFn(OnEat) --Runs a function when the player eats something.

    inst.components.eater.strongstomach = true -- can eat monster meat!
	
	inst:AddComponent("lootdropper")
    inst.components.lootdropper:SetChanceLootTable('maggotplayer')

	
	inst.spark_task = nil
    inst.spark_time = 0
    inst.spark_time_offset = 3
    inst.watchingrain = false
	inst.ghostbuild = "ghost_monster_build"
	inst.mobteleported = false
	inst.poisonimmune = true
	inst.foodcount = 0
	inst.isshiny = 0
	inst.hit_recovery = 0
	
	inst.OnSave = OnSave
	inst.OnLoad = OnLoad
	inst.OnPreLoad = OnPreload
	
	inst:ListenForEvent("ms_respawnedfromghost", onbecamerobot)
    inst:ListenForEvent("ms_becameghost", onbecameghost)
    --inst:ListenForEvent("death", ondeath)
	
	onbecamerobot(inst)
	
	--inst:AddTag("companion")
    --inst:AddTag("noauradamage")
    inst:RemoveTag("character")
	inst.mobsleep = true
	inst.poisonimmune = true
	inst.taunt = true
    --inst:AddTag("notraptrigger")
	inst:AddTag("lavae")
    --inst:AddTag("monster")
    --inst:AddTag("hostile")

	MakeCharacterPhysics(inst, 50, .5)
    inst.DynamicShadow:SetSize(2, 1)
    inst.Transform:SetSixFaced()

	--inst.Transform:SetScale(0.75, 0.75, 0.75)

    --inst.entity:SetPristine()
	
	inst.components.health.fire_damage_scale = 0    
	
	MakeLargeFreezableCharacter(inst)
	
    inst.userfunctions =
    {
        SetTeen = SetTeen,
        SetAdult = SetAdult,
    }
	
	------------------
    inst.isshiny = 0
    ------------------
	--(50, 129, 255)
	
  	local light = inst.entity:AddLight()
  	inst.Light:Enable(true)
	if inst.isshiny and inst.isshiny == 2 then
	inst.Light:SetRadius(1)
	inst.Light:SetFalloff(0.5)
	inst.Light:SetIntensity(0.75)
	inst.Light:SetColour(220/255, 0/255, 220/255)
	elseif inst.isshiny and inst.isshiny == 1 then
  	inst.Light:SetRadius(1)
	inst.Light:SetFalloff(0.5)
	inst.Light:SetIntensity(0.75)
	inst.Light:SetColour(50/255, 129/255, 255/255)
	else
	inst.Light:SetRadius(1)
	inst.Light:SetFalloff(0.5)
	inst.Light:SetIntensity(0.75)
	inst.Light:SetColour(235/255, 121/255, 12/255)
	end
	
	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(5, RestoreNightvision)
    end)
	
    return inst
	
end

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


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