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

public class Combat : EntityBehaviour
{
	[TagSelector] public string attackTag;
	public bool canLeaveHome = false;

	Entity enemy;
	Vector3 spawnPos;
	Matrix4x4 inverseSpawnMatrix;

	void Start() {
		inverseSpawnMatrix = transform.worldToLocalMatrix;
		spawnPos = transform.position;

		entity.triggerVision.onEnter += OnSeeEntity;
	}

	void FixedUpdate() {
		if (entity.isRolling) {
			entity.KeepRolling();
			return;
		}

		if (enemy) {
			Vector3 vec = enemy.transform.position - transform.position;
			Vector3 dir = vec.normalized;

			entity.Move(dir);
			entity.Turn(dir);

			if (!canLeaveHome) {
				Vector3 homePos = inverseSpawnMatrix.MultiplyPoint(transform.position);
				if (!entity.homeBounds.Contains(homePos)) {
					if (enemy) {
						Debug.Log($"{gameObject.name} abandoned {enemy.gameObject.name}.");
						enemy = null;
					}
				}
			}
		} else {
			entity.MoveToTarget(spawnPos, 0.5f);
		}
	}

	void OnSeeEntity(Collider other) {
		if (!enemy && attackTag != "" && other.gameObject.tag == attackTag) {
			enemy = other.GetComponent<Entity>();
			Debug.Log($"{gameObject.name} hates {other.gameObject.name}!");
		}
	}
}

