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

public class EnemyController : MonoBehaviour{

    public float speed;
    Vector2 velocity = Vector2.zero;
    [Range(0, .3f)] public float movementSmoothing = .1f;
    public GameObject bloodExplosion;

    public float turnTime;
    float time;
    float horizontalFacing = 1;

    GameObject player;
    Rigidbody2D rb2d;

    [Space]
    public Transform boxDetectionPos;
    public LayerMask whatIsPlayer;
    public float boxDetectionSize;
    bool playerDetected;
    bool detectPlayer;

    [Space]
    public Animator anim;

    // Start is called before the first frame update
    void Start(){
        rb2d = GetComponent<Rigidbody2D>();
    }

    bool dead;

    // Update is called once per frame
    void Update(){
        if (!playerDetected){
            time += Time.deltaTime;
            if (time >= turnTime){
                horizontalFacing *= -1;
                Flip(horizontalFacing);
                time = 0;
            }

            detectPlayer = Physics2D.OverlapCircle(boxDetectionPos.position, boxDetectionSize, whatIsPlayer);
            if (detectPlayer){
                anim.SetBool("Running", true);
                playerDetected = true;
            }
        }
        else{
            if(Mathf.Abs(player.transform.position.x - transform.position.x) >= .1f ){
                Flip(Mathf.RoundToInt(Mathf.Clamp((player.transform.position.x - transform.position.x) * 100, -1f, 1f)));
            }
        }
    }

    void FixedUpdate(){
        if (player != null && playerDetected && !dead){
            Vector2 targetVelocity = new Vector2(Mathf.RoundToInt(Mathf.Clamp(player.transform.position.x - transform.position.x, -1f, 1f)) * speed, rb2d.velocity.y);
            rb2d.velocity = Vector2.SmoothDamp(rb2d.velocity, targetVelocity, ref velocity, movementSmoothing);
        }
    }

    void Flip(float h){
        transform.localScale = new Vector3(Mathf.Abs(transform.localScale.x) * h, transform.localScale.y, transform.localScale.z);
    }

    public void WhoIsPlayer(GameObject player){
        this.player = player;
    }

    public void Die(){
        GetComponent<CapsuleCollider2D>().isTrigger = true;
        rb2d.velocity = Vector2.zero;
        rb2d.AddForce(new Vector2(-horizontalFacing * 10, 15), ForceMode2D.Impulse);
        Invoke("DeathExplode", 1);
        anim.SetTrigger("Die");
        dead = true;
    }

    void DeathExplode(){
        Instantiate(bloodExplosion, transform.position, Quaternion.identity);
        Destroy(gameObject);
    }

    void OnTriggerEnter2D(Collider2D col){
        if(col.gameObject.tag == "InstantDeath"){
            Die();
        }
    }

    void OnDrawGizmos(){
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(boxDetectionPos.position, boxDetectionSize);
    }
}
