using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BS;
using System.Linq;

enum CharacterControlMode
{
	DEFAULT,
	AIMING,
}

[RequireComponent(typeof(NodalPathfinding2DAgent))]
[RequireComponent(typeof(LineRenderer))]
public abstract class PlayableCharacter : Actor
{
	[SerializeField]
	private WeaponBehaviour weaponBehaviour = null;
	public bool isSelected = false;

	public Enemy Target { private get; set; }
	public bool isAutoTargeting = false;
	public LayerMask enemyMask;

	protected override void Start()
	{
		base.Start();
		if (weaponBehaviour == null)
			weaponBehaviour = GetComponent<WeaponBehaviour>();
		if (selectRing == null)
			selectRing = transform.Find("SelectRing").gameObject;
	}

	protected virtual void Update()
	{
		if (isSelected)
		{
			weaponBehaviour.DrawWeaponRange();
		}
		if (isAutoTargeting && Target == null)
		{
			AutoTargeting();
		}
		if (Target != null)
		{
			AttackTarget();
		}
	}

	public override void OnSelected()
	{
		if (isSelected)
			return;
		isSelected = true;
		selectRing?.SetActive(true);
		weaponBehaviour.OnSelected();
	}

	public override void OnUnselected()
	{
		isSelected = false;
		selectRing?.SetActive(false);
		weaponBehaviour.OnDeselected();
	}

	public override void MoveTo(Vector2 destination)
	{
		if (isSelected)
			agent.MoveTo(destination);
	}



	public void AutoTargeting()
	{
		Collider2D[] result = Physics2D.OverlapCircleAll(transform.position, weaponBehaviour.weapon.shotRange,enemyMask);
		List<Collider2D> sorted = result.ToList();
		sorted.Sort((a, b) =>
		Vector2.Distance(transform.position, a.transform.position) > Vector2.Distance(transform.position, b.transform.position) ? 1 : -1);

		foreach(var enemy in sorted)
		{
			
		}
	}

	public void SetTarget(Enemy enemy)
	{
		if(isSelected)
			Target = enemy;
	}

	public void AttackTarget()
	{
		if (weaponBehaviour.IsAttackable(Target))
		{
			agent.Stop();
			LookAt(Target.transform);
			weaponBehaviour.OnAttack(Target);
		}
		else
		{
			agent.MoveTo(Target.transform.position);
		}
	}

	protected void LookAt(Transform target)
	{
		transform.rotation = Quaternion.Euler(0, 0, Vector2.SignedAngle(Vector2.up, target.position - transform.position));
	}

	protected abstract void DefaultControl();
	protected abstract void AimingControl();
}
