using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity.Mathematics;
using UnityEngine;


public class AttackAnimatorFactory : MonoBehaviour {

  private Animator Melee;
  private Player Player;
  private bool AllowAttacks;
  protected FloatingTextSpawner TextPopUp;

  public void Awake() {
    Melee = GetComponent<Animator>();
    Player = GetComponentInParent<Player>();
    TextPopUp = new FloatingTextSpawner(this.transform);

  }

  public Action<GameObject> OnHit;
  private void OnTriggerEnter2D(Collider2D other) {
    if (!AllowAttacks) return;
    if (!other.CompareTag("EnemyHitBox")) return;
    Debug.Log($"Colliding with {other.gameObject.name}");
    TextPopUp.SpawnFloatingText($"Hit", Color.red, 3);
    OnHit?.Invoke(other.gameObject);
    ApplyKnockBack(other);
  }

  private void ApplyKnockBack(Collider2D other) {
    Rigidbody2D parentRb = other.transform.root.GetComponent<Rigidbody2D>();
    if (parentRb == null) return;
    Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector2 direction = mouseWorldPos - Player.transform.parent.gameObject.transform.position;
    parentRb.AddForce(direction * 10f, ForceMode2D.Impulse);
    //KnockbackUtility.ApplyKnockback(this, rb2D, hitDirection, 10f, 0.3f);
  }

  public void AllowAttack(int allow) {
    AllowAttacks = (allow == 1);
  }

  public void RotateTowardsMouse() {
    Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector2 direction = mouseWorldPos - Player.transform.position;
    float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(0, 0, angle - 180f);
  }

  public void MeleeResetKineticCharge() {
    Melee.CrossFade("Blank", 0, 1);
  }

  public void MeleeBasic(int set) {
    RotateTowardsMouse();

    if (set == 1) Melee.CrossFade("BasicAttack1", 0, 0);
    else if (set == 2) Melee.CrossFade("BasicAttack2", 0, 0);
    else if (set == 3) Melee.CrossFade("BasicAttack3", 0, 0);

    if (set == 1) Melee.CrossFade("KineticSurge1", 0, 1);
    else if (set == 2) Melee.CrossFade("KineticSurge2", 0, 1);
    else if (set == 3) Melee.CrossFade("KineticSurge3", 0, 1);
  }

  public void MeleeKineticSurge() {
    Melee.CrossFade("KineticSurgeRelease", 0, 0);
  }
}
