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

public class CleaverAI : EnemyBehaviour
{

    public class Phase : Singleton<Phase>
    {
        public Ticker changePhase = new Ticker(15);
        public bool isAwayPhase;

        private void Start()
        {
            changePhase.onTick.AddListener(() => isAwayPhase = !isAwayPhase);
        }
        private void Update()
        {
            changePhase.Tick(Time.deltaTime);
        }
    }
    [Header("Attack")]
    public Ticker attack = new Ticker(2);
    public float maxRandAttackDelay = 1.4f;

    [Header("Distancing")]
    public float awayDistance = 10f;
    public Vector3 posDelta;

    // private bool isPlayerAlive = true;

    // void Awake() {
    //     PlayerManager.I.playerDeath += OnPlayerDeath;
    // }

    // protected override void OnDestroy() {
    //     PlayerManager.I.playerDeath -= OnPlayerDeath;
    // }

    // private void OnPlayerDeath() {
    //     isPlayerAlive = false;
    // }

    private void Start()
    {
        attack.onTick.AddListener(Attack);
        // changePos.onTick.AddListener(ChangePos);
        Phase.I.changePhase.onTick.AddListener(ChangePos);
    }
    protected override void OnDestroy()
    {
        base.OnDestroy();
        Phase.I.changePhase.onTick.RemoveListener(ChangePos);
    }
    private void Update()
    {
        if (/* isPlayerAlive && */PlayerManager.I.unit != null)
        {
            if (PlayerManager.I.unit == unit) return;

            attack.Tick(Time.deltaTime);
            // changePos.Tick(Time.deltaTime);

            var player = PlayerManager.I.unit;

            unit.moveTarget = follow;
            unit.lookTarget = player.transform;

            if (Phase.I.isAwayPhase)
            {
                follow.position = player.transform.position + posDelta;
            }
            else
                follow.position = player.transform.position;
        }
    }

    public void Attack()
    {
        unit.Attack();
        attack.DelayTick(Random.value * maxRandAttackDelay);
    }
    public void ChangePos()
    {
        var x = Random.value * awayDistance;
        var z = Mathf.Sqrt(awayDistance * awayDistance - x * x);
        posDelta = new Vector3(x, 0, z);
    }
}
