using UnityEngine;
using System;
using Unity.VisualScripting;
using System.Linq;

public class PlayerCombatHandler : AttackerAndDamageable {

  public bool TakingDamage;
  protected FloatingTextSpawner TextPopUp;

  public PlayerCombatHandler() {
    BaseDamage = 10;
    AttackPreparationTime = 0.5f;
    AttackCooldownDuration = 1;

    BaseHealth = 100;
    CurrentHealth = BaseHealth;
    InvincibilityDuration = 0.11f;
    FrameFreezeDuration = 0.3f;
    IsKnockable = true;

    TextPopUp = new FloatingTextSpawner(Player.Instance.transform, 1);

    OnTakeDamage += (damage, dir) => InitializeTakenDamage();

    foreach (var material in Player.Instance.GetComponentsInChildren<SpriteRenderer>().Select(x => x.material).ToList()) {
      switch (material.name.Split(' ')[0]) {
        case "DamageFlashMat": Player.Instance.MaterialColorOverlay = material; break;
      }
    }
  }

  private void InitializeTakenDamage() {
    TextPopUp.SpawnFloatingText(DamageTaken.ToString(), Color.red, 3);
    TakingDamage = true;
  }

  public void ApplyKnockback() {
    if (IsInvincible) {
      var velocity = DirectionOfDamage * Knockback * 10 * InvincibilityLeft;
      var isWalkable = NavMeshUtils.IsWalkable(Player.Instance.Rigidbody.transform.position, DirectionOfDamage);
      Player.Instance.Rigidbody.linearVelocity = isWalkable ? velocity : Vector2.zero;
      Player.Instance.MaterialColorOverlay.SetFloat("_FlashAmount", InvincibilityLeft / InvincibilityDuration);
    } else {
      TakingDamage = false;
      Player.Instance.MaterialColorOverlay.SetFloat("_FlashAmount", 0);
      Player.Instance.Rigidbody.linearVelocity = Vector2.zero;
    }
  }

}
