using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCombatMobile : MonoBehaviour {
    public Animator animator;

    public Transform attackPoint;

    public LayerMask ennemyLayers;

    public float attackRange = 0.5f;
    public int attackDamagePlayer = 100;

    public float timeBtwAttack;
    public float startTimeBtwAttack;

    private bool canAttack = true;

    [SerializeField] private AudioClip sword = null;
    private AudioSource perso_AudioSource;

    public Joybutton joybutton;

    void Update () {

        //permet d'attaquer uniquement si le d�lai entre les deux attaques est arriv� � 0
        //si le joueur est au sol (il ne pas attaquer dans les airs)
        //on bloque les mouvements du joueur le temps de l'animation
        //on reactive quand l'animation d'attaque est fini
        if (timeBtwAttack <= 0) {
            if (joybutton.Pressed) {

                bool isGrounded = GetComponent<MoveCharacterMobile> ().isGrounded;
                if (isGrounded == true) {
                    MoveCharacterMobile.instance.enabled = false;
                    MoveCharacterMobile.instance.rb.velocity = Vector3.zero;
                    animator.SetFloat ("Speed", 0);
                    Attack ();
                    Debug.Log ("Attack");

                }
                Invoke ("canMove", 0.48f);
                timeBtwAttack = startTimeBtwAttack;

            }
        } else {
            timeBtwAttack -= Time.deltaTime;
        }
        perso_AudioSource = GetComponent<AudioSource> ();

    }

    void Attack () {
        if (!canAttack) return;
        //animation attaque
        animator.SetTrigger ("Attack");

        //detecte les ennemis � la port�e de l'attaque
        Collider2D[] hitEnemies = Physics2D.OverlapCircleAll (attackPoint.position, attackRange, ennemyLayers);

        perso_AudioSource.PlayOneShot (sword);
        
        ////et les d�truits
        foreach (Collider2D enemy in hitEnemies) {
            enemy.GetComponent<WeakSpot> ().TakeDamage (attackDamagePlayer);
        }

        canAttack = false;
        Invoke ("EnableAttack", 0.5f);
    }

    void OnDrawGizmosSelected () {
        if (attackPoint == null)
            return;

        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere (attackPoint.position, attackRange);
    }
    void EnableAttack () {
        canAttack = true;

    }

    void canMove () {
        MoveCharacterMobile.instance.enabled = true;

    }
}