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;


	#region Character Status Booleans
	private bool isOnlySelected = false;
	private bool isSelected = false;
	#endregion



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

	[SerializeField]
	private Skill[] m_skills = new Skill[4];
	public Skill[] Skills { get { return m_skills; } }

	protected override void Start()
	{
		base.Start();
		if (weaponBehaviour == null)
			weaponBehaviour = GetComponent<WeaponBehaviour>();
		if (selectRing == null)
			selectRing = transform.Find("SelectRing").gameObject;
		for (int i = 0; i < 4; i++)
		{
			m_skills[i] = Instantiate(m_skills[i]);
			m_skills[i].Init(this);
		}
	}

	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.OnUnselected();
		if (isOnlySelected)
		{
			IngameUIManager.inst.DisableCharacterStatusUI();
			isOnlySelected = false;
		}
	}

	public void OnOnlySelected()
	{
		OnSelected();
		isOnlySelected = true;
		IngameUIManager.inst.EnableCharacterStatusUI(this);
	}

	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));
	}

	public void UseSkill(int index)
	{
		if (isOnlySelected && m_skills[index].IsReady)
			m_skills[index].Aiming();
	}

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