using System.Collections;
using UnityEngine;
using Networking.Server;

public class HomingMissile : Projectile
{
    [SerializeField]
    ClientList Clients;

    public override IEnumerator ProjectileLogic(Character player, float animationTime, Vector3 direction)
    {
        Character target = findPlayer(player);

        yield return StartCoroutine(LerpTo(transform.position + Vector3.up * 2, 0.5f));
        yield return new WaitForSeconds(0.5f);

        if (target != null)
        {
            yield return StartCoroutine(LerpTo(target.transform.position, 1f));
            yield return PushPlayer(target);
        }
    }

    private IEnumerator PushPlayer(Character player)
    {
        Direction[] possibleDirections = DirectionExtras.RandomOrder();

        for (int i = 0; i < 4; i++)
        {
            if (Block.isBlockAtPosition(player.CurrentBlock.position + possibleDirections[i].ToVector() + Vector3.up, 1, ~0))
                continue;

            Debug.Log("Pushing player " + possibleDirections[i]);
            yield return StartCoroutine(player.CurrentBlock.DoPush(player, possibleDirections[i].ToVector()));
            break;
        }
    }

    private Character findPlayer(Character thisCharacter)
    {
        Character retVal = null;
   
        foreach (ClientData client in Clients)
        {
            if (client.Lives == 0 || client.playerCharacter.stuck || client.playerCharacter == thisCharacter)
                continue;

            if (retVal == null)
                retVal = client.playerCharacter;

            if (retVal.transform.position.x <= client.playerCharacter.transform.position.x)
                retVal = client.playerCharacter;
        }
        return retVal;
    }

    private IEnumerator LerpTo(Vector3 endPosition,float animationTime)
    {
        Vector3 startPosition = transform.position;
        float elapsedTime = 0;

        while (elapsedTime < animationTime)
        {

            transform.position = Vector3.Lerp(startPosition, endPosition, elapsedTime / animationTime);
            transform.LookAt(endPosition, Vector3.up);
            yield return new WaitForEndOfFrame();
            elapsedTime += Time.deltaTime;
        }
        transform.position = endPosition;
    }
}