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

public class Enemy : Actor
{
	private MeshRenderer mr = null;
	private MeshFilter mf = null;
	private Mesh eyesightMesh;
	public float eyesightRange = 5f;
	[Range(0, 360)]
	public int eyesightDegree = 60;

	[SerializeField]
	private List<Vector3> roamingPath;

	[SerializeField]
	private LayerMask blockEyesightMask;

#if UNITY_EDITOR
	private void OnDrawGizmos()
	{
		if (roamingPath.Count < 1)
			return;
		/*
		Gizmos.color = Color.white;
		Gizmos.DrawLine(transform.position, roamingPath[0]);
		for (int i = 0; i < roamingPath.Count; i++)
		{
			Gizmos.DrawLine(roamingPath[i], roamingPath[(i + 1) % roamingPath.Count]);
		}
		*/
	}
#endif

	protected override void Start()
	{
		base.Start();
		mr = GetComponentInChildren<MeshRenderer>();
		mf = GetComponentInChildren<MeshFilter>();
		eyesightMesh = new Mesh();
		mf.mesh = eyesightMesh;
		agent.SetPath(roamingPath);
	}

	private void Update()
	{
		UpdateEyesightMesh();
		if (agent.path.Count < 1)
			agent.SetPath(roamingPath);
	}

	private void UpdateEyesightMesh()
	{
		List<Vector3> vertices = new List<Vector3>();
		List<int> indices = new List<int>();

		vertices.Add(Vector3.zero);
		/*
		for (int i = -eyesightDegree / 2; i <= eyesightDegree / 2; i++)
		{
			RaycastHit2D hit = Physics2D.Raycast(transform.position, Quaternion.Euler(0, 0, i) * transform.up, eyesightRange, blockEyesightMask);
			
			if (hit.collider == null)
				vertices.Add((Quaternion.Euler(0, 0, i) * Vector3.up) * eyesightRange);
			else
			{
				Quaternion quat = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, -transform.rotation.eulerAngles.z);
				vertices.Add(quat * (hit.point - new Vector2(transform.position.x, transform.position.y)));
			}
		}
		*/

		for (int i = -eyesightDegree / 2; i <= eyesightDegree / 2; i++)
		{
			RaycastHit2D hit = Physics2D.Raycast(transform.position, Quaternion.Euler(0, 0, i) * transform.up, eyesightRange, blockEyesightMask);

			if (hit.collider == null)
				vertices.Add((Quaternion.Euler(0, 0, i) * Vector3.up) * eyesightRange);
			else
			{
				Quaternion quat = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, -transform.rotation.eulerAngles.z);
				vertices.Add(quat * (hit.point - new Vector2(transform.position.x, transform.position.y)));
			}
		}

		for (int i = 0; i < vertices.Count - 2; i++)
		{
			indices.Add(0);
			indices.Add(i + 2);
			indices.Add(i + 1);
		}
		eyesightMesh.SetVertices(vertices);
		eyesightMesh.SetTriangles(indices, 0);
	}

	public override void OnSelected()
	{
		throw new System.NotImplementedException();
	}

	public override void OnUnselected()
	{
		throw new System.NotImplementedException();
	}
}
