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

public class LucertolaBehaviour : MonoBehaviour
{

    public float backAndForthTimer = 0f;
    public float speed = 150f;
    private bool isFacingRight = true;
    private Rigidbody2D rb;
    private PlayerAnimationHandler handler;
    private bool isStunned = false;
    private float stunTimer = 3f;
    private GameObject enemySpit;
    private Transform mouth;
    private PolygonCollider2D coneCast;
    public bool isStatic = false;
    public GameObject projectile;
    private bool isShooting = false;
    private float shootCooldownTimer = 1f;
    private bool IsUsingTimer
    {
        get
        {
            return backAndForthTimer > 0f && !isStatic;
        }
    }
    public float circleRadius =  180f;

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        if (IsUsingTimer)
        {
            StartCoroutine(BackAndForthTimer());
        } 
        else 
        {
            StartCoroutine(BackAndForthCollision());
        }

        handler = new PlayerAnimationHandler(gameObject);
        mouth = transform.Find("Mouth");
        coneCast = mouth.GetComponent<PolygonCollider2D>();
    }

    // Update is called once per frame
    void Update()
    {
        transform.localScale = new Vector3(isFacingRight ? 1 : -1, transform.localScale.y, transform.localScale.z);

        if (rb.velocity.x == 0)
        {
            Debug.Log("fermo");
            handler.SetIdle();
        }
        else if (rb.velocity.x != 0 && rb.velocity.y == 0)
        {
            handler.SetMovement();
            Debug.Log("movimento laterale");
        }
        var player = CheckPlayer();
        if (player != null)
        {
            if (!isShooting && !isStunned)
            {
                StartCoroutine(ShootCooldown());
                Shoot(player.position);
            }

        }



    }

    private void Shoot( Vector3 position)
    {
        Debug.Log("TI SPAROOO" + position);
        var proj = Instantiate(projectile);
        proj.GetComponent<EnemyProjectileBehaviour>().Shoot(mouth.position, position);
    }

    private Transform CheckPlayer()
    {
        if (isStatic)
        {
            return CheckPlayerCircle();
        }
        return CheckPlayerRay();
    }

    private Transform CheckPlayerCircle()
    {
        var colliders  = Physics2D.OverlapCircleAll(mouth.transform.position, circleRadius);
        foreach (var coll in colliders)
        {
            if (coll.tag == "Player")
            {
                Debug.Log("ECCOTI CERCHIO");
                return coll.transform;
            }
        }
        return null;
    }

    private Transform CheckPlayerRay()
    {
        var cf = new ContactFilter2D();
        var colliders = new Collider2D[10];
        coneCast.OverlapCollider(cf, colliders);
        Debug.Log(colliders);
        foreach (var coll in colliders)
        {
            if (coll != null && coll.tag == "Player")
            {
                Debug.Log("ECCOTI!");
                return coll.transform;
            }
        }
        return null;
    }

    /* non usata al momento */
    private IEnumerator BackAndForthTimer()
    {
        yield return null;
        while(true)
        {
            var t = backAndForthTimer;
            var direction = isFacingRight ? new Vector3(1, 0, 0) : new Vector3(-1, 0, 0);
            while (t>=0)
            {
                transform.position += direction * speed * Time.deltaTime;
                t -= Time.deltaTime;
                yield return null;
            }
            isFacingRight = !isFacingRight;
        }
    }

    private IEnumerator BackAndForthCollision()
    {
        yield return null;
        while (true)
        {
            var direction = isFacingRight ? new Vector3(1, 0, 0) : new Vector3(-1, 0, 0);
            if (isStunned)
            {
                rb.velocity = Vector2.zero;
            }
            else
            {
                rb.velocity = direction * speed;
            }
            yield return null;
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Player" && !isStunned)
        {
            SceneManager.LoadScene("Menu");
        }
        else if (collision.tag == "Environment" && !IsUsingTimer)
        {
            Debug.Log("se lo fa dice cose brutte a papà");
            isFacingRight = !isFacingRight;
        }
    }

    public void Stun()
    {
        isStunned = true;
        StartCoroutine(StunCoroutine());
    }

    private IEnumerator StunCoroutine() 
    {
        Physics2D.IgnoreLayerCollision(9, 10, true);
        Physics2D.IgnoreLayerCollision(13, 10, true);
        var t = stunTimer;
        while (t >= 0)
        {
            t -= Time.deltaTime;
            yield return null;
        }
        isStunned = false;
        Physics2D.IgnoreLayerCollision(9, 10, false);
        Physics2D.IgnoreLayerCollision(13, 10, false);
        yield return null;
    }

    private IEnumerator ShootCooldown()
    {
        isShooting = true;
        yield return null;
        var t = shootCooldownTimer;
        while (t >= 0)
        {
            t -= Time.deltaTime;
            yield return null;

        }
        isShooting = false;
        yield return null;

    }


}
