::ROOT <- getroottable()

if("RootblightCallbacks" in ROOT) {
    return
}

::TOOLTIP_GATE_TANK <- "Yellow tanks will instantly cap the gate. Stop them at all costs!"
::TOOLTIP_BOSS <- "Defeat all giants to remove the boss's uber!"

::MaxPlayers <- MaxClients().tointeger()
::MaxWeapons <- 8
::hBossEnt <- null

//Ensures every player has a scope so that squirrel doesn't get upset
for (local i = 1; i <= MaxPlayers ; i++)
{
	local player = PlayerInstanceFromIndex(i)
	if (player == null) continue
	player.ValidateScriptScope()
}

::AngleNormalize <- function( angle )
{
	angle = angle % 360.0
	if (angle > 180) 
	{
		angle -= 360
	}
	if (angle < -180)
	{
		angle += 360
	}
	return angle
}

::BossThink <- function()
{
     if(NetProps.GetPropInt(self, "m_lifeState") != 0) {
        NetProps.SetPropString(self, "m_iszScriptThinkFunction", "")
        hBossEnt = null
        hBonemergeModel.Kill()
        self.SetCustomModelWithClassAnimations("")
        NetProps.SetPropInt(self, "m_nRenderMode", 0)
	    NetProps.SetPropInt(self, "m_clrRender", 0xFFFFFF)
        return 30000
    }

    self.RemoveCondEx(51, true)

    // hBossAnnotation.SetAbsOrigin(self.GetOrigin() + Vector(0, 0, 100))

    hBonemergeModel.AcceptInput("SetParent", "!activator", self, self)

    for (local hRocket; hRocket = Entities.FindByClassname(hRocket, "tf_projectile_rocket");)
    {
        local hOriginalLauncher = NetProps.GetPropEntity(hRocket, "m_hOriginalLauncher")
        if(hOriginalLauncher == null || !(hOriginalLauncher.IsValid())) continue
        if (hOriginalLauncher.GetOwner() != self)
            continue

        local scope = hRocket.GetScriptScope()

        if(scope == null) {
            hRocket.ValidateScriptScope()
            scope = hRocket.GetScriptScope()
        }

        if("hBigRocketProp" in scope) {
            if(!NetProps.GetPropInt(hRocket, "m_iDeflected")) {
                continue
            }

            if(scope.bHasSkinSwapped) {
                continue
            }

            scope.bHasSkinSwapped = true

            scope.hBigRocketProp.SetSkin(0)

            continue
        }

        scope.bHasSkinSwapped <- false
        
        scope.hBigRocketProp <- SpawnEntityFromTable("prop_dynamic", {
            model           = "models/workshop/player/items/soldier/taunt_rocket_jockey/taunt_rocket_jockey.mdl"
            origin          = hRocket.GetCenter() + Vector(0, 0, -24)
            disableshadows  = 1
            skin            = 1
        })

        scope.hBigRocketProp.AcceptInput("SetParent", "!activator", hRocket, hRocket)
        scope.hBigRocketProp.SetAbsOrigin(hRocket.GetCenter() + Vector(0, 0, -24))
        local qDesiredAngles = hRocket.GetAbsAngles() + QAngle(0, 90, 0)
        qDesiredAngles.z = AngleNormalize(qDesiredAngles.x)
        qDesiredAngles.y = AngleNormalize(qDesiredAngles.y)
        qDesiredAngles.x = 0
        scope.hBigRocketProp.SetAbsAngles(qDesiredAngles)

        RootblightCallbacks.SetDestroyCallback(hRocket, function() {
            local destroyCallbackScope = self.GetScriptScope()
            delete destroyCallbackScope.bHasSkinSwapped
            delete destroyCallbackScope.hBigRocketProp
            //Exploded, not deflected or short circuit'd or medic shield'd
            if(self.IsSolidFlagSet(4)) {
                DispatchParticleEffect("hightower_explosion", self.GetCenter(), Vector())
            }
        })
    }

    return -1
}

::hBossMusic1 <- null
::hBossMusic2 <- null

function ROOT::GetWeaponInSlot(pPlayer, pSlot) {
    for (local i = 0; i < MaxWeapons; i++)
	{
		local heldWeapon = NetProps.GetPropEntityArray(pPlayer, "m_hMyWeapons", i)
		if (heldWeapon == null)
			continue
		if (heldWeapon.GetSlot() != pSlot)
			continue
		return heldWeapon
	}
}

function ROOT::ForceTaunt(player, taunt_id)
{
	local weapon = Entities.CreateByClassname("tf_weapon_bat")
	local active_weapon = player.GetActiveWeapon()
	player.StopTaunt(true) // both are needed to fully clear the taunt
	player.RemoveCond(7)
	weapon.DispatchSpawn()
	NetProps.SetPropInt(weapon, "m_AttributeManager.m_Item.m_iItemDefinitionIndex", taunt_id)
	NetProps.SetPropBool(weapon, "m_AttributeManager.m_Item.m_bInitialized", true)
	NetProps.SetPropBool(weapon, "m_bForcePurgeFixedupStrings", true)
	NetProps.SetPropEntity(player, "m_hActiveWeapon", weapon)
	NetProps.SetPropInt(player, "m_iFOV", 0) // fix sniper rifles
	player.HandleTauntCommand(0)
	NetProps.SetPropEntity(player, "m_hActiveWeapon", active_weapon)
	weapon.Kill()
}

function ROOT::ShowTankAnnotation() {
    local hTankAnnotation = SpawnEntityFromTable("training_annotation", {
        targetname = "tank_hint"
        display_text = TOOLTIP_GATE_TANK
        lifetime = 8
        origin = Vector(-5763, -2697, 123)
    })

    hTankAnnotation.AcceptInput("Show", null, null, null)
}

function ROOT::PlayBossMusic() {
    hBossMusic1 = SpawnEntityFromTable("ambient_generic", {
        targetname = "boss_music"
        message = "#ui\\gamestartup4.mp3"
        health = 10
        spawnflags = 17
    })

    hBossMusic2 = SpawnEntityFromTable("ambient_generic", {
        targetname = "boss_music"
        message = "#ui\\gamestartup4.mp3"
        health = 10
        spawnflags = 17
    })
    
    hBossMusic1.AcceptInput("PlaySound", null, null, null)
    hBossMusic2.AcceptInput("PlaySound", null, null, null)
}

function ROOT::StopBossTauntDelayed() {
    if(hBossEnt == null) return

    EntFire("tf_gamerules", "PlayVO", "vo\\mvm\\mght\\soldier_mvm_m_go02.mp3", 1) 
    EntFire("tf_gamerules", "PlayVO", "vo\\mvm\\mght\\soldier_mvm_m_helpmecapture03.mp3", 4)
    EntFireByHandle(hBossEnt, "RunScriptCode", "activator.RemoveCondEx(7, true)", 5, hBossEnt, hBossEnt)
    hBossEnt.AddCustomAttribute("voice pitch scale", 1, -1)
}

function ROOT::BossUnleashRage() {
    if(hBossEnt == null) return

    hBossEnt.AddCustomAttribute("voice pitch scale", 0, -1)
    EntFireByHandle(hBossEnt, "RunScriptCode", "ForceTaunt(activator, 31441)", 1, hBossEnt, hBossEnt)
    EntFire("tf_gamerules", "PlayVO", "vo\\mvm\\mght\\soldier_mvm_m_paincrticialdeath02.mp3", 1)
    EntFire("tf_gamerules", "PlayVO", "player\\invulnerable_off.wav", 4)
    EntFire("bignet", "CallScriptFunction", "RageBossStats", 6)
    EntFire("bignet", "CallScriptFunction", "RageBossBeginSpeak", 14)
    EntFire("tf_gamerules", "PlayVO", "vo\\mvm\\mght\taunts\\soldier_mvm_m_taunts05.mp3", 6)
    EntFireByHandle(hBossEnt, "RunScriptCode", "activator.RemoveCondEx(52, true)", 5, hBossEnt, hBossEnt)
    hBossEnt.RemoveBotAttribute(2)
}

function ROOT::RageBossStats() {
    if(hBossEnt == null) return

    hBossEnt.RemoveCondEx(7, true)

    hBossEnt.SetCustomModelWithClassAnimations("models/bots/soldier_boss/bot_soldier_boss.mdl")
    
    local hRocketLauncher = GetWeaponInSlot(hBossEnt, 0)
    hRocketLauncher.AddAttribute("faster reload rate", 2.55, -1)
    hRocketLauncher.AddAttribute("projectile speed increased", 0.4, -1)
    hBossEnt.AddCustomAttribute("move speed bonus", 0.5, -1)
    hBossEnt.AddCustomAttribute("cannot pick up intelligence", 0, -1)
    hBossEnt.AddCustomAttribute("no_jump", 0, -1)
    hBossEnt.AddCustomAttribute("increased jump height", 1, -1)
    hBossEnt.RemoveBotAttribute( Constants.FTFBotAttributeType.AGGRESSIVE )
    hBossEnt.SetMission(0, true)
}

function ROOT::RageBossBeginSpeak() {
    if(hBossEnt == null) return

    hBossEnt.AddCustomAttribute("voice pitch scale", 1, -1)
}

function ROOT::BossEntrance(pParticleName)
{
	DispatchParticleEffect(pParticleName, Vector(-6767, -1781, 50), Vector(90, 0, 0))
    EntFire("tf_gamerules", "PlayVO", "mvm\\mvm_tele_activate.wav", 0)
    EntFire("tf_gamerules", "PlayVO", "vo\\mvm\\mght\\soldier_mvm_m_laughlong01.mp3", 0)
}

::RootblightCallbacks <- {
    OnGameEvent_mvm_wave_complete = function(_) {
        if(hBossMusic1 == null) return

        hBossMusic1.AcceptInput("StopSound", null, null, null)
        hBossMusic2.AcceptInput("StopSound", null, null, null)
        hBossMusic1.Kill()
        hBossMusic2.Kill()
        hBossMusic1 = null
        hBossMusic2 = null
    }

    function SetDestroyCallback(entity, callback)
    {
        entity.ValidateScriptScope();
        local scope = entity.GetScriptScope();
        scope.setdelegate({}.setdelegate({
                parent   = scope.getdelegate()
                id       = entity.GetScriptId()
                index    = entity.entindex()
                callback = callback
                _get = function(k)
                {
                    return parent[k];
                }
                _delslot = function(k)
                {
                    if (k == id)
                    {
                        entity = EntIndexToHScript(index);
                        local scope = entity.GetScriptScope();
                        scope.self <- entity;
                        callback.pcall(scope);
                    }
                    delete parent[k];
                }
            })
        );
    }
    function OnGameEvent_player_spawn(params)
    {
        local player = GetPlayerFromUserID(params.userid)
        if (!player) return
        if (!IsPlayerABot(player)) return
        EntFireByHandle(player, "RunScriptCode", "RootblightCallbacks.BossInit(activator)", -1, player, player)
    }

    BossInit = function(player) {
		if(!player.HasBotTag("atomic_boss")) {
			return
		}

        EntFire("tf_gamerules", "PlayVO", "mvm\\giant_heavy\\giant_heavy_entrance.wav", 0)
        EntFire("tf_gamerules", "PlayVO", "misc\\halloween\\spell_mirv_explode_primary.wav", 0)

        local scope = player.GetScriptScope()

        player.SetCustomModelWithClassAnimations("models/player/soldier.mdl")

        //We've changed the boss model to use human soldier model in order to use human animations.
        //We're going to make a bonemerged gsoldier model to pretend it's still gsoldierbot
        local hBonemergeModel = SpawnEntityFromTable("tf_wearable", {})
        local nGiantSoldierModel = PrecacheModel("models/bots/soldier_boss/bot_soldier_boss.mdl")
        NetProps.SetPropInt(hBonemergeModel, "m_nModelIndex", nGiantSoldierModel)
        NetProps.SetPropInt(hBonemergeModel, "m_fEffects", 129)
        NetProps.SetPropBool(hBonemergeModel, "m_bValidatedAttachedEntity", true)
        NetProps.SetPropEntity(hBonemergeModel, "m_hOwnerEntity", player)

        hBonemergeModel.SetTeam(3)
        hBonemergeModel.SetOwner(player)

        DispatchSpawn(hBonemergeModel)

        //Turn the player invisible so we only see the gsoldier bot
        NetProps.SetPropInt(player, "m_nRenderMode", 1)
	    NetProps.SetPropInt(player, "m_clrRender", 0)

        scope.hBonemergeModel <- hBonemergeModel

        hBonemergeModel.AcceptInput("SetParent", "!activator", player, player)

		player.Teleport(true, Vector(-6767, -1781, 60), false, QAngle(), false, Vector())

        player.AddCondEx(52, 99999, null)

        scope.hBossAnnotation <- SpawnEntityFromTable("training_annotation", {
            targetname = "boss_hint"
            display_text = TOOLTIP_BOSS
            lifetime = 10
            origin = player.GetOrigin() + Vector(0, 0, 100)
        })

        EntFire("tf_gamerules", "PlayVO", "mvm\\mvm_tele_deliver.wav", 0)
        EntFire("tf_gamerules", "PlayVO", "player\\invulnerable_on.wav", 1)
        EntFire("tf_gamerules", "PlayVO", "vo\\mvm\\mght\taunts\\soldier_mvm_m_taunts16.mp3", 1)
        EntFireByHandle(scope.hBossAnnotation, "Show", null, 1, null, null)
        EntFireByHandle(player, "RunScriptCode", "ForceTaunt(activator, 31521)", 1, player, player)

        scope.bossThink <- BossThink
        AddThinkToEnt(player, "bossThink")

        hBossEnt = player
	}
}

__CollectGameEventCallbacks(RootblightCallbacks)