require "prefabutil"
local assets =
{
	Asset("ANIM", "anim/tent.zip"),
}

SetSharedLootTable( 'riventent',
{
	{'spear',          1.00},
	{'armorwood',          1.00},
	{'footballhat',          1.00},
	{'smallmeat_dried',          1.00},
	{'smallmeat_dried',          1.00},
	{'smallmeat_dried',          1.00},
	{'smallmeat_dried',          1.00},
	{'smallmeat_dried',          1.00},
	{'goldnugget',          1.00},
	{'goldnugget',          1.00},
	{'goldnugget',          1.00},
	{'purplegem',          0.02},
	{'bluegem',          0.10},
	{'redgem',          0.10},
	{'orangegem',          0.02},
	{'yellowgem',          0.02},
	{'greengem',          0.02},
	{'rivensoulball',          0.05},
	{'rivensoulballwhite',          0.05},
})

local function OnDay(inst)
    if inst.components.spawner:IsOccupied() then
        if inst.doortask then
            inst.doortask:Cancel()
            inst.doortask = nil
        end
        inst.doortask = inst:DoTaskInTime(1 + math.random()*2, function() inst.components.spawner:ReleaseChild() end)
    end
end

local function onhammered(inst, worker)
	if inst:HasTag("fire") and inst.components.burnable then
		inst.components.burnable:Extinguish()
	end
	inst.components.lootdropper:DropLoot()
	shitswap("collapse_big").Transform:SetPosition(inst.Transform:GetWorldPosition())
	inst.SoundEmitter:PlaySound("dontstarve/common/destroy_wood")
	inst:Remove()
end

local function SpawnGuardHound(inst, attacker)
    local prefab = inst.components.childspawner.childname
    local defender = inst.components.childspawner:SpawnChild(attacker, prefab)
    if defender and attacker and defender.components.combat then
        defender.components.combat:SetTarget(attacker)
        defender.components.combat:BlankOutAttacks(1.5 + math.random()*2)
    end
end

local function onhit(inst, worker)
	if inst.components.childspawner then
	    local num_to_release = inst.components.childspawner.childreninside
	    for k = 1,num_to_release do
	        SpawnGuardHound(inst,worker)
	    end
	end
    local attacker = worker
    if attacker then
        inst.components.combat:ShareTarget(attacker, 30, function(dude)
            return dude:HasTag(inst.belongtowhich) and not dude:HasTag("character")
                   and not dude.components.health:IsDead()
                   and (not attacker:HasTag(inst.belongtowhich) and not attacker:HasTag("character") )
        end, 10)
    end
	if not inst:HasTag("burnt") then
		inst.AnimState:PlayAnimation("hit")
		inst.AnimState:PushAnimation("idle", true)
	end
end

local function onfinished(inst)
	if not inst:HasTag("burnt") then
		inst.AnimState:PlayAnimation("destroy")
		inst:ListenForEvent("animover", function(inst, data) inst:Remove() end)
		inst.SoundEmitter:PlaySound("dontstarve/common/tent_dis_pre")
		inst.persists = false
		inst:DoTaskInTime(16*FRAMES, function() inst.SoundEmitter:PlaySound("dontstarve/common/tent_dis_twirl") end)
	end
end

local function onbuilt(inst)
	inst.AnimState:PlayAnimation("place")
	inst.AnimState:PushAnimation("idle", true)
end


local function onsleep(inst, sleeper)
	if GetClock():IsDay() then
		local tosay = "ANNOUNCE_NODAYSLEEP"
		if GetWorld():IsCave() then
			tosay = "ANNOUNCE_NODAYSLEEP_CAVE"
		end
		if sleeper.components.talker then
			sleeper.components.talker:Say(GetString(sleeper.prefab, tosay))
			return
		end
	end

	if inst:HasTag("fire") then
		if sleeper.components.talker then
			sleeper.components.talker:Say(GetString(sleeper.prefab, "ANNOUNCE_NOSLEEPONFIRE"))
		end
		return
	end
	
	local hounded = GetWorld().components.hounded

	local danger = FindEntity(inst, 10, function(target) 
		return
			(target:HasTag("monster") and not target:HasTag("player") and not sleeper:HasTag("spiderwhisperer"))
			or (target:HasTag("monster") and not target:HasTag("player") and sleeper:HasTag("spiderwhisperer") and not target:HasTag("spider"))
			or (target:HasTag("pig") and not target:HasTag("player") and sleeper:HasTag("spiderwhisperer"))
			or (target.components.combat and target.components.combat.target == sleeper)
	end)
	
	if hounded and (hounded.warning or hounded.timetoattack <= 0) then
		danger = true
	end
	
	if danger then
		if sleeper.components.talker then
			sleeper.components.talker:Say(GetString(sleeper.prefab, "ANNOUNCE_NODANGERSLEEP"))
		end
		return
	end

	if sleeper.components.hunger.current < TUNING.CALORIES_MED then
		sleeper.components.talker:Say(GetString(sleeper.prefab, "ANNOUNCE_NOHUNGERSLEEP"))
		return
	end
	
	sleeper.components.health:SetInvincible(true)
	sleeper.components.playercontroller:Enable(false)

	GetPlayer().HUD:Hide()
	TheFrontEnd:Fade(false,1)

	inst:DoTaskInTime(1.2, function() 
		
		GetPlayer().HUD:Show()
		TheFrontEnd:Fade(true,1) 
		
		if GetClock():IsDay() then

			local tosay = "ANNOUNCE_NODAYSLEEP"
			if GetWorld():IsCave() then
				tosay = "ANNOUNCE_NODAYSLEEP_CAVE"
			end

			if sleeper.components.talker then				
				sleeper.components.talker:Say(GetString(sleeper.prefab, tosay))
				sleeper.components.health:SetInvincible(false)
				sleeper.components.playercontroller:Enable(true)
				return
			end
		end
		
		if sleeper.components.sanity then
			sleeper.components.sanity:DoDelta(TUNING.SANITY_HUGE)
		end
		
		if sleeper.components.hunger then
			sleeper.components.hunger:DoDelta(-TUNING.CALORIES_HUGE, false, true)
		end
		
		if sleeper.components.health then
			sleeper.components.health:DoDelta(TUNING.HEALING_HUGE, false, "tent", true)
		end
		
	if inst:HasTag("DLC") then	
		if sleeper.components.temperature and sleeper.components.temperature.current < TUNING.TARGET_SLEEP_TEMP then
			sleeper.components.temperature:SetTemperature(TUNING.TARGET_SLEEP_TEMP)
		end	
		local moisture_start = nil
		if sleeper.components.moisture and sleeper.components.moisture:GetMoisture() > 0 then
			moisture_start = sleeper.components.moisture.moisture
		end		
	elseif inst:HasTag("DLC") then
		if sleeper.components.temperature then
			sleeper.components.temperature:SetTemperature(sleeper.components.temperature.maxtemp)
		end end

		inst.components.finiteuses:Use()
		GetClock():MakeNextDay()
		
	if inst:HasTag("DLC") then	
		if moisture_start then
			sleeper.components.moisture.moisture = moisture_start - TUNING.SLEEP_MOISTURE_DELTA
			if sleeper.components.moisture.moisture < 0 then sleeper.components.moisture.moisture = 0 end
		end
		end
			if sleeper:HasTag("musha") then
sleeper.stamina = sleeper.stamina * 0 + 101
sleeper.fatigue = sleeper.fatigue * 0
if sleeper.music <=100 then
sleeper.music = sleeper.music + 50
if sleeper.music >=100 then
sleeper.music = sleeper.music *0 + 100
sleeper:AddTag("switlight")
end
elseif sleeper.music >=100 then
sleeper.music = sleeper.music *0 + 100
sleeper:AddTag("switlight")
end
end		
		sleeper.components.health:SetInvincible(false)
		sleeper.components.playercontroller:Enable(true)
		sleeper.sg:GoToState("wakeup")	
	end)
end

local function onsave(inst, data)
	if inst:HasTag("burnt") or inst:HasTag("fire") then
        data.burnt = true
    end
end

local function onload(inst, data)
	if data and data.burnt then
        inst.components.burnable.onburnt(inst)
    end
end
local function fn(Sim)
	local inst = CreateEntity()
	inst.belonger = 'riven'
	local trans = inst.entity:AddTransform()
	local anim = inst.entity:AddAnimState()
	inst.entity:AddSoundEmitter()
	inst:AddTag("tent")    
    MakeObstaclePhysics(inst, 1)    
    inst:AddTag("structure")
    anim:SetBank("tent")
    anim:SetBuild("tent")
    anim:PlayAnimation("idle", true)
    
	local minimap = inst.entity:AddMiniMapEntity()
	minimap:SetIcon( "tent.png" )
    
    inst:AddComponent("inspectable")

    inst:AddComponent("lootdropper")
    inst.components.lootdropper:SetChanceLootTable('riventent')

    inst:AddComponent("workable")
    inst.components.workable:SetWorkAction(ACTIONS.HAMMER)
    inst.components.workable:SetWorkLeft(4)
	inst.components.workable:SetOnFinishCallback(onhammered)
	inst.components.workable:SetOnWorkCallback(onhit)

	inst:AddComponent("finiteuses")
	inst:AddComponent("combat")
    inst.components.finiteuses:SetMaxUses(TUNING.TENT_USES)
    inst.components.finiteuses:SetUses(TUNING.TENT_USES)
    inst.components.finiteuses:SetOnFinished( onfinished )
	MakeSnowCovered(inst, .01)
	inst:ListenForEvent( "onbuilt", onbuilt)
	MakeLargeBurnable(inst, nil, nil, true)
	MakeLargePropagator(inst)
	inst.OnSave = onsave 
    inst.OnLoad = onload
	inst:ListenForEvent("entitysleep", function ()
		if SaveGameIndex and SaveGameIndex.IsModeShipwrecked and SaveGameIndex:IsModeShipwrecked() then
			local pos = Vector3(inst.Transform:GetWorldPosition())
			local start_angle = math.random()*PI*2
			local rad = 0.5
			if inst.Physics then
				rad = rad + inst.Physics:GetRadius()
			end
			local offset = FindWalkableOffset(pos, start_angle, rad, 8, false)
			local isCursorWet=inst:GetIsOnWater(inst.Transform:GetWorldPosition())
			local invalidpos = offset == nil or isCursorWet
			if invalidpos then
				inst:Remove()
				return
			end
		end
		if inst.checking then
			inst.checking:Cancel()
			inst.checking=nil
		end
	    inst.checking = inst:DoPeriodicTask(2,function ()
		    if TUNING.LOLLOAD then
		    	inst:AddComponent("characterspecific")
		    	if TUNING.LOLCHAR then
		    		if GetPlayer().prefab~=inst.belonger then
		    			local inneed = string.gsub(inst.prefab, inst.belonger, GetPlayer().prefab)
			    		local result = shitswap(inneed)
			    		result.Transform:SetPosition(inst.Transform:GetWorldPosition())
		    		end
		    	end
			    if inst.checking then
				    inst.checking:Cancel()
				    inst.checking=nil
			    end
	    		inst.components.characterspecific:SetOwner(inst.belonger)
		    end
	    end)
    end)
    return inst
end
local function fn1(Sim)
	local inst = fn(Sim)
	inst.name = "Demacia Tent"
	inst.AnimState:SetMultColour(0,0,1,1)
	inst:AddComponent("childspawner")
    inst.components.childspawner.childname = "rivenmemberd"
    inst.components.childspawner:StartSpawning()
    inst.components.childspawner.spawnoffscreen=false
    inst.belongtowhich="demaciamem"
    if inst.belongtowhich == TUNING.RIVENBELONG then
	    inst.components.childspawner:SetRegenPeriod(TUNING.SEG_TIME*8)
	    inst.components.childspawner:SetSpawnPeriod(TUNING.SEG_TIME*2)
	    inst.components.childspawner:SetMaxChildren(1)
    else
	    inst.components.childspawner:SetRegenPeriod(TUNING.SEG_TIME*3)
	    inst.components.childspawner:SetSpawnPeriod(TUNING.SEG_TIME*2)
	    inst.components.childspawner:SetMaxChildren(math.random(3, 5))
    end
	return inst
end

local function fn2(Sim)
	local inst = fn(Sim)
	inst.name = "Noxus Tent"
	inst.AnimState:SetMultColour(1,0,0,1)
	inst:AddComponent("childspawner")
    inst.components.childspawner.childname = "rivenmembern"
    inst.components.childspawner:StartSpawning()
    inst.components.childspawner.spawnoffscreen=false
    inst.belongtowhich="noxusmem"
    if inst.belongtowhich == TUNING.RIVENBELONG then
	    inst.components.childspawner:SetRegenPeriod(TUNING.SEG_TIME*8)
	    inst.components.childspawner:SetSpawnPeriod(TUNING.SEG_TIME*2)
	    inst.components.childspawner:SetMaxChildren(1)
    else
	    inst.components.childspawner:SetRegenPeriod(TUNING.SEG_TIME*3)
	    inst.components.childspawner:SetSpawnPeriod(TUNING.SEG_TIME*2)
	    inst.components.childspawner:SetMaxChildren(math.random(3, 5))
    end
	return inst
end

return Prefab( "common/objects/riventent1", fn1, assets),
	   Prefab( "common/objects/riventent2", fn2, assets),
		MakePlacer( "common/tent_placer", "tent", "tent", "idle" ) 
