local MakePlayerCharacter = require "prefabs/player_common"

local assets = {
    Asset("ANIM", "anim/dragonfly_build.zip"),
    Asset("ANIM", "anim/dragonfly_fire_build.zip"),
    Asset("ANIM", "anim/dragonfly_basic.zip"),
    Asset("ANIM", "anim/dragonfly_actions.zip"),
	--------------------
	Asset("ANIM", "anim/dragonfly_shiny_build_01.zip"),
	Asset("ANIM", "anim/dragonfly_shiny_build_02.zip"),
	Asset("ANIM", "anim/dragonfly_fire_shiny_build_01.zip"),
	Asset("ANIM", "anim/dragonfly_fire_shiny_build_02.zip"),
}
local prefabs = 
{

}
local start_inv = 
{
   
}

SetSharedLootTable( 'dragonplayer',
{
    {'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(0)
	inst.Light:SetFalloff(.1)
	inst.Light:SetIntensity(.1)
	inst.Light:SetColour(245/255,40/255,0/255)
	end, inst)
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: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

------------------------------------------------------

local function SetSkinOverride(inst)
	if inst.isshiny == 2 then
		inst.AnimState:SetBuild("dragonfly_shiny_build_02")
	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("dragonfly_shiny_build_0"..inst.isshiny)
			end		
		end
	end	
end
------------------------------------------------------

local function setChar(inst)
if not inst:HasTag("playerghost") then
    inst.AnimState:SetBank("dragonfly")
    inst.AnimState:SetBuild("dragonfly_build")
    inst:SetStateGraph("SGdragonplayer")
end	
	if MOBPVPMODE == "Enable" then
		PvPTeleport(inst)
	end
	inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
	if inst.userid == "KU_6_7BRh4a" and inst.isshiny == 0 or inst.isshiny == 2 then --KU_6_7BRh4a
		inst.isshiny = 2
		inst.AnimState:SetBuild("dragonfly_shiny_build_02")
	end
	inst.components.locomotor.fasteronroad = false
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( "dragonplayer.tex" )
	
	inst:DoTaskInTime(0, function()
	if ThePlayer then
		inst:EnableMovementPrediction(false)
	end
end)
	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)
	
	inst:WatchWorldState( "issummer", function() SetSandstormImmunity(inst) end) --makes immune to Sandstorm visual issues.
	
	SetSandstormImmunity(inst)
	
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 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 ~= "Enable" then
		inst.components.propagator:StartSpreading()
	end
	
    inst.components.moisture:DoDelta(-inst.components.moisture:GetMoisture())


    --if inst.reverttask then
        --inst.reverttask:Cancel()
       -- inst.reverttask = nil
   -- end

    --inst.reverttask = inst:DoTaskInTime(TUNING.DRAGONFLY_ENRAGE_DURATION, 
        --function() if inst.enraged then 
            --inst:PushEvent("transform", {transformstate = "normal"})
        --end end)
end

local function DontTriggerCreep(inst)
    inst.components.locomotor.walkspeed = (TUNING.DRAGONFLY_SPEED)	
end

local master_postinit = function(inst)
    inst.components.health:SetMaxHealth(5000)
	--inst:AddComponent("healthRegenerate")
	--inst:ListenForEvent("equip", drop)
    inst.components.combat:SetAttackPeriod(TUNING.DRAGONFLY_ATTACK_PERIOD)
    inst.components.locomotor.walkspeed = TUNING.DRAGONFLY_SPEED
	inst.components.combat:SetDefaultDamage(75*2)
    inst.components.temperature.inherentinsulation = -TUNING.INSULATION_SMALL
	
	inst.specialatk2 = true
	inst.dragonrage = false
	inst.mobsleep = true
	
	inst.poisonimmune = true
	inst:AddTag("dragonplayer")
	inst:AddTag("flying")
	inst:AddTag("epic")
	--inst:AddTag("mobplayer")
	--inst:AddTag("special_atk2")
    inst:AddComponent("groundpounder")
    inst:AddComponent("knownlocations")
    inst:AddComponent("grouptargeter")
    inst:AddComponent("damagetracker")
    inst:AddComponent("stunnable")
    inst:AddComponent("healthtrigger")
    inst:AddComponent("rampingspawner")
	
    inst:AddComponent("homeseeker")
    inst:AddComponent("timer")
	inst.TransformFire = TransformFire
    inst.TransformNormal = TransformNormal
	inst.SoundEmitter:PlaySound("dontstarve_DLC001/creatures/dragonfly/fly", "flying")
	inst.AnimState:SetBuild("dragonfly_build")
	inst.OnSetSkin = function(skin_name)
    inst.AnimState:SetBuild("dragonfly_build")
	inst:SetStateGraph("SGdragonplayer")
	end
	inst.AnimState:SetBank("dragonfly")
	--inst:SetStateGraph("SGdragonplayer")
	inst.components.talker:IgnoreAll()
	inst.components.locomotor:SetTriggersCreep(false)
	inst.components.hunger:Pause()
	inst.components.sanity.ignore = true
    inst.DynamicShadow:SetSize(6, 3.5)
    inst.Transform:SetSixFaced()
    inst.Transform:SetScale(1.3,1.3,1.3)
    MakeFlyingGiantCharacterPhysics(inst, 500, 1.4)
	inst.hit_recovery = 2
	
	
	
	inst:AddComponent("lootdropper")
	inst.components.lootdropper:SetChanceLootTable('dragonplayer')
	
	
	local start_spawning = function()
        inst:PushEvent("transform", {transformstate = "normal"})
        inst.components.rampingspawner:Start() 
    end


    inst.components.groundpounder.numRings = 2
	--inst.components.groundpounder.damageRings = 3
	if MOBFIRE ~= "Enable" then
		inst.components.groundpounder.burner = true
	end    
    inst.components.groundpounder.groundpoundfx = "firesplash_fx"
    inst.components.groundpounder.groundpounddamagemult = 1.25
    inst.components.groundpounder.groundpoundringfx = "firering_fx"
	inst.components.groundpounder.noTags = {"lavae"}

    inst.components.combat:SetDefaultDamage(80*2)
    inst.components.combat:SetAttackPeriod(TUNING.DRAGONFLY_ATTACK_PERIOD)
    inst.components.combat.playerdamagepercent = MOBPVP
    --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.dragonrage = false
	
	inst.components.temperature.maxtemp = 60
	inst.components.temperature.mintemp = 30
	
	inst.components.eater:SetDiet({ FOODTYPE.MEAT, FOODTYPE.BURNT }, { FOODTYPE.MEAT, FOODTYPE.BURNT }) 
    inst.components.eater:SetCanEatHorrible()

    inst.components.eater.strongstomach = true -- can eat monster meat!
	
    MakeHugeFreezableCharacter(inst)
    inst.components.freezable:SetResistance(TUNING.DRAGONFLY_FREEZE_THRESHOLD)
    inst.components.freezable.damagetobreak = TUNING.DRAGONFLY_FREEZE_RESIST
	
	inst.ghostbuild = "ghost_monster_build"
	inst.mobteleported = false
	inst.isshiny = 0
	
	inst.OnSave = OnSave
	inst.OnLoad = OnLoad

    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:AddComponent("playercontroller")
	--inst:AddComponent("playeractionpicker")
	--inst.components.playercontroller.actionbuttonoverride = BossActionButton
	--inst.components.playeractionpicker.rightclickoverride = LeftClickPicker
	--inst.components.playeractionpicker.rightclickoverride = RightClickPicker
	--inst:AddComponent("worker")
	--inst.components.worker:SetAction(ACTIONS.DIG, 1)
	--inst.components.worker:SetAction(ACTIONS.CHOP, 20)
	--inst.components.worker:SetAction(ACTIONS.MINE, 20)
	--inst.components.worker:SetAction(ACTIONS.HAMMER, 20)

	inst.level = 0

	inst.components.eater.ignoresspoilage = true
	
  	local light = inst.entity:AddLight()
  	inst.Light:Enable(false)
  	inst.Light:SetRadius(0)
  	inst.Light:SetFalloff(0.9)
  	inst.Light:SetIntensity(0.6)
  	inst.Light:SetColour(180/255,195/255,150/255)

  	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, DontTriggerCreep)
        inst:DoTaskInTime(5, setChar)
		inst:DoTaskInTime(5.1, setSkin)
		inst:DoTaskInTime(6, RemovePenalty)
		inst:DoTaskInTime(10, RestoreNightvision)
    end)
	
    return inst
	
end

if SKIN_RARITY_COLORS.ModMade ~= nil then
AddModCharacterSkin("dragonplayer", 1, {normal_skin = "dragonfly_shiny_build_01", ghost_skin = "ghost_monster_build"}, {"dragonfly_shiny_build_01", "ghost_monster_build"}, {"DRAGONPLAYER", "FORMAL"})
end

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