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 playerDistanceThreshold = 0.1f;
    public float dodgeTime = 0.2f;
    float dodgeTimer = 0;
    public LayerMask linecastLayer;
    float offset;
    private void Awake()
    {
        dodgeTimer = dodgeTime;
        offset = Random.Range(-0.5f,0.5f);
    }


    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 if(hit.collider.tag == "Obstacle")
        {
            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) < playerDistanceThreshold)
            {
                GameManager.GameOver();
                return;
            }
        }

        Vector3 direction = (GameManager.Player.position - new Vector3(-offset/2f,offset,0) - transform.position).normalized;
        float rot_z = Mathf.Atan2(direction.y,direction.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0,0,rot_z+180);
        if (dodgeTimer < dodgeTime)
        {
            dodgeTimer += Time.deltaTime;

            if (dodgeTimer > dodgeTime/100f || true)
            {
                debugColor = Color.red;
                Vector3 new_direction = (hit.point - (Vector2)transform.position).normalized;
                transform.Translate(-new_direction * moveSpeed * 1.2f, Space.World);
                return;
            }
        }

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

    }
}
