local MakePlayerCharacter = require "prefabs/player_common"

local assets = 
{
	Asset("ANIM", "anim/merm_shiny_build_01.zip"),
}
local prefabs = {	
    }
	
local start_inv = {
	"fish",
	"fish",
	"froglegs",
}

SetSharedLootTable('mermplayer',
{
    {"fish", 1.00},
	{"froglegs", 1.00},
    
})

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

local function OnAttacked(inst, data)
        inst.components.combat:SetTarget(data.attacker)
        inst.components.combat:ShareTarget(data.attacker, 30, CanShareTarget, 5)
 end


local function RestoreNightvision(inst)

	inst:DoTaskInTime(3, function(inst) 
	inst.Light:Enable(false)
	inst.Light:SetRadius(0)
	inst.Light:SetFalloff(.5)
	inst.Light:SetIntensity(.6)
	inst.Light:SetColour(245/255,40/255,0/255)
	end, inst)
end

local function MoistureDetection (inst)
 if inst.components.moisture ~= nil and inst.components.moisture:GetMoisture() > 0 then
	inst.components.temperature.mintemp = 20
	inst.components.temperature.hurtrate = 0
	
	end 
end

local function dorainsparks(inst, dt)
    if inst.components.moisture ~= nil and inst.components.moisture:GetMoisture() > 0 then
	
		inst.components.temperature.mintemp = 20
		
        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
                1 or
                1,
                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 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.components.temperature.mintemp = 0
        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

    --Override with overcharge light values
    --inst.Light:Enable(false)
    --inst.Light:SetRadius(2)
    --inst.Light:SetFalloff(0.75)
    --inst.Light:SetIntensity(.9)
    --inst.Light:SetColour(235 / 255, 121 / 255, 12 / 255)
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

    if inst.watchingrain then
        inst.watchingrain = false
        inst:StopWatchingWorldState("israining", onisraining)
    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

------------------------------------------------------
----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.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("merm_shiny_build_0"..inst.isshiny)
			end		
		end
	end	
end

local function setChar(inst)
	if not inst:HasTag("playerghost") then
    inst.AnimState:SetBank("pigman")
    inst.AnimState:SetBuild("merm_build")
    inst:SetStateGraph("SGmermplayer")
	end
	--inst.components.hunger:Pause()
	if MOBPVPMODE == "Enable" then
		PvPTeleport(inst)
	end
	inst.components.locomotor.fasteronroad = false
	--inst.components.sanity.ignore = true
end

local NIGHTVISION_COLOURCUBES =
{
    day = "images/colour_cubes/insane_day_cc.tex",
    dusk = "images/colour_cubes/insane_dusk_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:IsCave() 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 common_postinit = function(inst) 
	inst.soundsname = "wilson"

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

	inst:DoTaskInTime(0, function()
   if ThePlayer then
      inst:EnableMovementPrediction(false)
   end
end)
end

local function Equip(inst)
    local head = inst.components.inventory:GetEquippedItem(EQUIPSLOTS.HEAD)
	if head then

	inst.AnimState:Show("HEAD")
        
		
	end 
	
end

local function DontTriggerCreep(inst)
    inst.components.locomotor.runspeed = (TUNING.MERM_RUN_SPEED)
	--inst.components.locomotor:SetSlowMultiplier( 1 )
    --inst.components.locomotor:SetTriggersCreep(false)
    --inst.components.locomotor.pathcaps = { ignorecreep = true }
end


local master_postinit = function(inst)
    inst.components.health:SetMaxHealth(200)
	inst.components.hunger:SetMax(125)
	inst.components.sanity:SetMax(200)
	--inst:AddComponent("healthRegenerate")
	inst.components.combat.playerdamagepercent = MOBPVP
	inst.components.combat.pvp_damagemod = 1 --disables second pvp override.
    --inst.components.combat:SetAttackPeriod(TUNING.HOUND_ATTACK_PERIOD)
	inst.components.combat:SetRange(TUNING.WORM_ATTACK_DIST)
    inst.components.locomotor.runspeed = (TUNING.MERM_RUN_SPEED)
	inst.components.combat:SetDefaultDamage(40)
	--inst.components.combat:SetHurtSound("dontstarve/creatures/hound/hit")
	--inst.components.temperature.hurtrate = 0
    inst.components.temperature.inherentinsulation = -TUNING.INSULATION_SMALL
	inst.AnimState:SetBank("pigman")
	inst.AnimState:SetBuild("merm_build")	
	inst.OnSetSkin = function(skin_name)
    inst.AnimState:SetBuild("merm_build")
	inst:SetStateGraph("SGmermplayer")
	
	inst:ListenForEvent("ms_respawnedfromghost", DontTriggerCreep)
    DontTriggerCreep(inst)

	
	end
	inst:SetStateGraph("SGmermplayer")
	
	--inst:AddComponent("locomotor")
    --inst.components.locomotor:SetSlowMultiplier( 1 )
    --inst.components.locomotor:SetTriggersCreep(false)
    --inst.components.locomotor.pathcaps = { ignorecreep = true }
	
	MoistureDetection(inst)
	
	inst.components.locomotor:SetShouldRun(true)
	inst.components.talker:IgnoreAll()
	--inst.components.hunger:Pause()
	--inst.components.sanity.ignore = true
	--inst.HUD.controls.status.stomach:Hide()
	
	MakeMediumBurnableCharacter(inst, "pig_torso")
    MakeMediumFreezableCharacter(inst, "pig_torso")
	
	inst.components.eater:SetCanEatHorrible()
	
	inst.components.eater.strongstomach = true -- can eat monster meat!

	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.components.sanity.night_drain_mult = 0.75
	
	inst.isshiny = 0
	
	inst.OnSave = OnSave
	inst.OnLoad = OnLoad	
	
	inst:ListenForEvent("ms_respawnedfromghost", onbecamerobot)
	inst:ListenForEvent("attacked", OnAttacked)
	
	onbecamerobot(inst)
	
	inst:AddComponent("lootdropper")
    inst.components.lootdropper:SetChanceLootTable('mermplayer')
	--inst.components.health.fire_damage_scale = 0 -- Take no damage from fire 
	
	 
	inst:AddTag("character")
    inst:AddTag("merm")
    --inst:AddTag("wet")
	--inst:AddTag("mobplayer")
	inst:AddTag("mermplayer")
	
	--inst.poisonimmune = true
	inst.taunt = true
	inst.specialsleep = true
	inst.specialatk2 = true
	
	--inst:ListenForEvent("attacked", OnAttacked)
	
	MakeCharacterPhysics(inst, 50, .5)
    inst.DynamicShadow:SetSize(1.5, .75)
    inst.Transform:SetFourFaced()
	
	
	--inst.components.temperature.maxtemp = 60
	--inst.components.temperature.mintemp = 20
	--inst.components.moisture:SetInherentWaterproofness(1)
	
	--inst.AnimState:Show("Head")
    --inst.AnimState:Show("HatFX")
	
	inst:ListenForEvent("equip", Equip)
    
	
	------------------
    
    ------------------

	
  	local light = inst.entity:AddLight() --Can't see at night but is immune to Grue
  	inst.Light:Enable(false)
  	inst.Light:SetRadius(0)
  	inst.Light:SetFalloff(0.6)
  	inst.Light:SetIntensity(0.6)
  	inst.Light:SetColour(180/255,195/255,255/255)
	
	--No nightvision, makes a need for lightsources during the night to work.
  	--inst:WatchWorldState( "isday", function() SetNightVision(inst) end)
  	--inst:WatchWorldState( "isdusk", function() SetNightVision(inst) end)
  	--inst:WatchWorldState( "isnight", function() SetNightVision(inst)  end)
	
	--SetNightVision(inst, true)
	
	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, DontTriggerCreep)
		inst:DoTaskInTime(6, RemovePenalty)
		inst:DoTaskInTime(10, RestoreNightvision)
    end)
	
	
    return inst
	
end


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

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