using EventAttributes.Events.Raiding;
using Terraria;
using TerrariaApi.Server;
using TShockAPI;
using System.Collections.Generic;
using Org.BouncyCastle.Crmf;
using EventAttributes.EventStats;
using System.Linq;

namespace EventAttributes
{
    public static class DisableAllyProjectiles
    {
        private static readonly HashSet<(int, bool)> NoWantAllyProjectiles = new HashSet<(int, bool)>();
        private static readonly HashSet<int> HookProjectileIDs = new() { 13, 32, 73, 74, 230, 231, 232, 233, 234, 235, 256, 315, 322, 331, 332, 372, 396, 446, 486, 487, 488, 489, 646, 647, 648, 649, 652, 753, 865, 935 };
        private static readonly HashSet<int> ServerSpawnedProjectiles = new(); /* Hashset and not single buffer in case multiple projectiles are added atomically */

        internal static void DisableAllyProjectile(SendDataEventArgs args)
        {
            int projIndex = args.number;
            if (projIndex < 0 || projIndex >= Terraria.Main.maxProjectiles)
                return;

            var proj = Terraria.Main.projectile[projIndex];

            if (proj == null)
                return;

            int Hash = proj.GetHashCode();
            try
            {
                if (!proj.active)
                    return;

                if (HookProjectileIDs.Contains(proj.type)) // The projectile is a hook, hooks should always be synced
                {
                    return;
                }

                TSPlayer? ownerTS = SafeGetPlayer(proj.owner);

                // (Do NOT early-return for args.remoteClient == proj.owner)

                // If the owner is using event-stats AND the projectile heals, do not filter at all -- the player should be able to see their ally healing them.
                bool ownerUsingEStatsHealer =
                    (ownerTS?.GetData<EventStats_Player>(EventAttributes.EventStatsPlayerKey)?.GetUsingEStats() ?? false)
                    && (HealProjectileMain.HealProjectile.ContainsKey(proj.type)
                        || HealProjectileMain.HealProjectilePercentOverrides.ContainsKey(proj.type));
                if (ownerUsingEStatsHealer)
                    return;

                /* 
                 * Boss projectiles never filtered. Players can't use projectiles 
                 * the raid bosses can, so there's no concern of the player using 
                 * a projectile that can be ignored.
                 */
                foreach (var raid in Raids.GetCopyOfOnGoingRaids())
                    if (raid.BossProjectiles.Contains(proj.type))
                        return;

                bool isEnemyProj = proj.hostile || proj.npcProj;
                if (isEnemyProj)
                    return; // only filter ally projectiles

                bool ServerSpawnedProj = ServerSpawnedProjectiles.Contains(Hash);

                bool allowOwnerExemption = false || ServerSpawnedProj; /*|| (NoWantAllyProjectiles.Where(x => x.Item1 == (ownerTS?.Account?.ID ?? -1))?.FirstOrDefault().Item2 ?? false)*//* (proj.type is 696 or 695 or 694 && EventAttributes.SSJs.ContainsKey(ownerTS?.Index ?? -1));*/



                int msg = (int)args.MsgId;
                var text = args.text;
                int number = args.number;
                float number2 = args.number2;
                float number3 = args.number3;
                float number4 = args.number4;
                int number5 = args.number5;
                int number6 = args.number6;
                int number7 = args.number7;

                if (args.remoteClient == -1)
                {
                    // We take over delivery completely to guarantee filtering.
                    args.Handled = true;

                    /* This is the only time we should send back a player their own owned-projectile; usually when the server spawns it on their behalf, so it must explicitly tell them its theirs */
                    if (allowOwnerExemption)
                    {
                        NetMessage.SendData(msg, proj.owner, -1, text,
                            number, number2, number3, number4, number5, number6, number7);
                    }

                    for (int i = 0; i < TShock.Players.Length; i++)
                    {
                        var receivingPlayer = SafeGetPlayer(i);
                        if (receivingPlayer == null || receivingPlayer.Account == null)
                            continue;

                        /* do not send back the player their own projectile */
                        if (i == proj.owner)
                            continue;

                        /* if the player is in pvp, no projectiles should be hidden so they don't see themselves taking damage from nothing */
                       if (receivingPlayer.TPlayer.hostile)
                        {
                            NetMessage.SendData(msg, i, -1, text,
                                number, number2, number3, number4, number5, number6, number7);
                            continue;
                        }

                        bool optedIn = NoWantAllyProjectiles.Any(x => x.Item1 == receivingPlayer.Account.ID);

                        if (optedIn && proj.owner != i)
                            continue;

                        NetMessage.SendData(msg, i, -1, text,
                            number, number2, number3, number4, number5, number6, number7);
                    }

                    return;
                }
                else
                {
                    var ts = SafeGetPlayer(args.remoteClient);
                    if (ts == null) return;

                    // If the recipient is the owner, drop ally projectiles unless explicitly exempted.
                    if (ts.Index == proj.owner)
                    {
                        if (!allowOwnerExemption)
                        {
                            args.Handled = true; // drop for owner
                        }
                        return; // either dropped or let vanilla proceed in the exemption case
                    }

                    if (ts.TPlayer.hostile)
                        return;

                    // Recipient is not owner: apply opt-in filter.
                    bool optedIn = ts.Account != null && NoWantAllyProjectiles.Any(x => x.Item1 == ts.Account.ID);
                    if (optedIn)
                    {
                        args.Handled = true; // drop for this client
                    }
                    // else: vanilla delivery continues
                }
            }
            finally 
            {
                ServerSpawnedProjectiles.Remove(Hash);
            }
        }


        /* add server side projectile */
        public static void AddSSP(int ProjectileHash) 
        {
            lock (ServerSpawnedProjectiles) 
            { 
                ServerSpawnedProjectiles.Add(ProjectileHash);
            }
        }
       


        private static TSPlayer? SafeGetPlayer(int index)
        {
            if (index < 0 || index >= TShock.Players.Length) return null;
            var p = TShock.Players[index];
            return (p != null && p.Active) ? p : null;
        }

        internal static void DaPCommand(CommandArgs args)
        {
            if (args.Player.Account == null || !args.Player.IsLoggedIn)
            {
                args.Player.SendErrorMessage("You must be logged in to use this command!");
                return;
            }

            int accountId = args.Player.Account.ID;

            if (args.Parameters.Count == 0)
            {
                // Toggle basic ally projectile filter (sendtoself = false)
                if (NoWantAllyProjectiles.Any(x => x.Item1 == accountId))
                {
                    NoWantAllyProjectiles.RemoveWhere(x => x.Item1 == accountId);
                    args.Player.SendSuccessMessage("You will now see all ally projectiles.");
                }
                else
                {
                    NoWantAllyProjectiles.Add((accountId, false));
                    args.Player.SendSuccessMessage("You will no longer see ally projectiles (except when PvP is enabled).");
                }
                return;
            }

            if (args.Parameters[0].Equals("debug", StringComparison.OrdinalIgnoreCase) && args.Player.HasPermission("*"))
            {
                args.Player.SendInfoMessage("Dap Debug:");
                args.Player.SendInfoMessage($"There are {ServerSpawnedProjectiles.Count} Hashes present in ServerSpawnedProjectiles: {string.Join(", ", ServerSpawnedProjectiles)}.");
                args.Player.SendInfoMessage($"There are {HealProjectileMain.ServerSpawnedProjectileHashes.Count} Hashes present in HealProjectileMain.ServerSpawnedProjectileHashes: {string.Join(", ", HealProjectileMain.ServerSpawnedProjectileHashes)}.");
                return;
            }
            /*            args.Player.SendErrorMessage($"Invalid /dap flag specified: {args.Parameters[0]}. Valid flags: forcesendtoself, (sts) — forces the server to send your own projectiles back to you. This may reduce projectiles disappearing when using server Enchantments. (Do not use if you have anything less than a great connection!)");
            */
            args.Player.SendErrorMessage("Invalid syntax! Usage: /dap.");
            return;
        }

    }
}