using System;
using Actions;
using UnityEngine;
using UnityEngine.Serialization;

public class UnitAnimator : MonoBehaviour {
    private static readonly int isWalking = Animator.StringToHash("IsWalking");
    private static readonly int shoot = Animator.StringToHash("Shoot");
    private static readonly int swordSlash = Animator.StringToHash("SwordSlash");
    [SerializeField] private Animator animator;
    [SerializeField] private Transform bulletProjectilePrefab;

    [SerializeField] private Transform rifleTransform;
    [SerializeField] private Transform swordTransform;

    [FormerlySerializedAs("shootPoint")] [SerializeField]
    private Transform shootPointTransform;

    private void Awake() {
        if (TryGetComponent(out MoveAction moveAction)) {
            moveAction.OnStartMoving += MoveAction_OnStartMoving;
            moveAction.OnStopMoving += MoveAction_OnStopMoving;
        }

        if (TryGetComponent(out ShootAction shootAction)) {
            shootAction.OnShoot += ShootAction_OnShoot;
        }

        if (TryGetComponent(out SwordAction swordAction)) {
            swordAction.OnSwordActionStarted += SwordAction_OnSwordActionStarted;
            swordAction.OnSwordActionCompleted += SwordAction_OnSwordActionCompleted;
        }
    }

    private void Start() => EquipRifle();

    private void SwordAction_OnSwordActionStarted(object sender, EventArgs e) {
        EquipSword();
        animator.SetTrigger(swordSlash);
    }

    private void SwordAction_OnSwordActionCompleted(object sender, EventArgs e) => EquipRifle();

    private void MoveAction_OnStartMoving(object sender, EventArgs e) => animator.SetBool(isWalking, true);
    private void MoveAction_OnStopMoving(object sender, EventArgs e) => animator.SetBool(isWalking, false);

    private void ShootAction_OnShoot(object sender, ShootAction.ShootEventArgs e) {
        animator.SetTrigger(shoot);
        Transform bulletProjectPrefab = Instantiate(bulletProjectilePrefab, shootPointTransform.position, Quaternion.identity);
        Vector3 targetUnitShootAtPosition = e.TargetUnit.GetWorldPosition();
        targetUnitShootAtPosition.y = shootPointTransform.position.y;
        bulletProjectPrefab.GetComponent<BulletProjectile>().Setup(targetUnitShootAtPosition);
    }

    private void EquipSword() {
        swordTransform.gameObject.SetActive(true);
        rifleTransform.gameObject.SetActive(false);
    }

    private void EquipRifle() {
        rifleTransform.gameObject.SetActive(true);
        swordTransform.gameObject.SetActive(false);
    }
}