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

public class Enemy : MonoBehaviour
{
    public float moveSpeed = 0.1f;
    public bool canSeePlayer = false;
    public float distanceThreshold = 0.1f;
    public float dodgeTime = 0.2f;
    float dodgeTimer = 0;
    public LayerMask linecastLayer;
    private void Awake()
    {
        dodgeTimer = dodgeTime;
    }


    Color debugColor = Color.white;

    void FixedUpdate()
    {
        if (GameManager.Player == null) { return; }

        


        RaycastHit2D hit = Physics2D.Linecast(transform.position, GameManager.Player.position, linecastLayer);
        if (hit.collider == null) {
            canSeePlayer = true;
        } else if (hit.collider.transform == GameManager.Player.transform)
        {
            canSeePlayer = true;
        }
        else
        {
            canSeePlayer = false;
            float distanceToBarrier = Vector2.Distance(transform.position, hit.point);
            if (distanceToBarrier < distanceThreshold)
            {
                dodgeTimer = 0;
            }
            Debug.DrawLine(transform.position, hit.point, debugColor);
        }

        if (canSeePlayer)
        {
            if (Vector2.Distance(GameManager.Player.position, transform.position) < distanceThreshold*5)
            {
                GameManager.GameOver();
                return;
            }
        }

        Vector3 direction = (GameManager.Player.position - new Vector3(0,0.5f,0) - transform.position).normalized;

        if (dodgeTimer < dodgeTime)
        {
            dodgeTimer += Time.deltaTime;

            if (dodgeTimer > dodgeTime/100f)
            {
                debugColor = Color.red;
                transform.Translate(new Vector3(-direction.x, direction.y) * moveSpeed * 1.2f);
                return;
            }
        }

        transform.Translate(direction * moveSpeed);
        debugColor = Color.white;

    }
}
