using Photon.Pun;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class CastingStateController : MonoBehaviour
{
    public bool isCasting;
    public PlayerMovement playerMovement;
    public LayerMask movementMask;

    Camera cam;
    Ray ray;
    RaycastHit hit;

    PhotonView photonView;
    ProjectileSpawnLocationController projectileSpawnLocationController;

    private void Awake()
    {
        cam = Camera.main;
        photonView = GetComponentInParent<PhotonView>();
        projectileSpawnLocationController = transform.root.GetComponentInChildren<ProjectileSpawnLocationController>();
    }
    private void Start()
    {
        if (!photonView.IsMine) this.enabled = false;
    }
    public void RequestAbilityCast(BaseAbility ability, Action abilityExecution)
    {
        if (isCasting) return;

        if (!ability.castableWhileMoving)
            playerMovement.ToggleAgentMoving(true);

        StartCoroutine(Casting(ability, abilityExecution));
    }
    public void RequestAbilityChannel(BaseAbility channeledAbility, Action abilityChannelExecution)
    {
        if (isCasting) return;

        if (!channeledAbility.castableWhileMoving)
            playerMovement.ToggleAgentMoving(true);

        StartCoroutine(Channeling(channeledAbility, abilityChannelExecution));
    }

    private IEnumerator Casting(BaseAbility ability, Action abilityExecution)
    {
        isCasting = true;
        CastBarHandler.Instance.ShowCastBar(ability, abilityExecution);

        playerMovement.InstantFaceCast(projectileSpawnLocationController.GetLookat());

        //cast animation
        yield return new WaitForSeconds(ability.castTime);

        if (ability.animationType != AbilityAnimationType.Melee)
        {
            abilityExecution.Invoke();

            isCasting = false;
            if (!ability.castableWhileMoving)
                playerMovement.ToggleAgentMoving(false);
        }

        Debug.Log("$$sCastbar Done casting");
    }

    private IEnumerator Channeling(BaseAbility channeledAbility, Action abilityChannelExecution)
    {
        isCasting = true;
        CastBarHandler.Instance.ShowChannelingBar(channeledAbility, abilityChannelExecution);

        playerMovement.InstantFaceCast(projectileSpawnLocationController.GetLookat());

        abilityChannelExecution.Invoke();

        if (!channeledAbility.castableWhileMoving)
            playerMovement.ToggleAgentMoving(true);

        yield return null;
    }

    public void ResetChannelingCast()
    {
        isCasting = false;
        playerMovement.ToggleAgentMoving(false);
    }

    public void ResetCastingOnMeleeAnimationEvent()
    {
        isCasting = false;
        playerMovement.ToggleAgentMoving(false);
        StopAllCoroutines();
        Debug.Log("$$ResetCastingState On Event");
    }
}
