using UnityEngine;
using System.Collections.Generic;
using Kryz.CharacterStats.Examples;
using Kryz.CharacterStats;

[CreateAssetMenu(fileName = "DamageOverTimeEffect", menuName = "RiftMayhem/AbilitySystem/Effects/Damage Over Time Effect", order = 1)]
public class DamageOverTimeEffect : StatusEffect
{
    [Space]
    public float baseDamagePerTick;
    public float tickRate = 1f;
    public DamageOverTimeType damageType;

    private float finalTickValue;
    private CharacterStats stats;

    public override void ApplyEffect(Taggable user, List<Taggable> targets)
    {
        base.ApplyEffect(user, targets);

        finalTickValue = CalculateFinalDamage(user);

        if (applyToTargetsHit)
        {
            foreach (Taggable target in targets)
            {
                BaseDamageOverTimeEffectInstance dotInstance = GetOrAddCorrectInstance(target);
                dotInstance.owner.RPC((nameof(dotInstance.RPC_ApplyDamageOverTimeEffect)+damageType.ToString()), dotInstance.owner.Owner, StatusEffectIndexer.Instance.StatusEffects.IndexOf(this), finalTickValue);
            }
        }
        if (applyToSelf)
        {
            BaseDamageOverTimeEffectInstance dotInstance = GetOrAddCorrectInstance(user);
            dotInstance.ApplyEffect(this, finalTickValue);
        }
    }

    private BaseDamageOverTimeEffectInstance GetOrAddCorrectInstance(Taggable target)
    {
        switch (damageType)
        {
            case DamageOverTimeType.Burn:
                return target.GetComponent<BurnEffectInstance>() ?? target.gameObject.AddComponent<BurnEffectInstance>();
            case DamageOverTimeType.Poison:
                return target.GetComponent<PoisonEffectInstance>() ?? target.gameObject.AddComponent<PoisonEffectInstance>();
            case DamageOverTimeType.Bleed:
                return target.GetComponent<BleedEffectInstance>() ?? target.gameObject.AddComponent<BleedEffectInstance>();
            default:
                throw new System.ArgumentException("Unknown damage type");
        }
    }

    private float CalculateFinalDamage(Taggable user)
    {
        float finalDamage = baseDamagePerTick;
        CharacterStats stats = user.GetComponent<CharacterStats>();

        foreach (var statInfluence in influencingStats)
        {
            if (stats.statsDictionary.TryGetValue(statInfluence.statTag.name.ToLower(), out CharacterStat stat))
            {
                finalDamage += stat.Value * statInfluence.percentInfluence;
            }
        }

        return finalDamage;
    }

}