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


public class ShootingCannon : ActiveBlock
{
    [Header("Cannon Settings")]
    public bool shootingRight;
    public GameObject shootingObject;
    public Transform spawnLocation;
    public TextMeshPro counter;
    public TextMeshPro counter2;
    int countdowntimer = 3;
    int countdown;

    public override int GetInitative()
    {
        //order
        return 4;
    }

    private void Start()
    {
        countdown = countdowntimer;
    }
    private void Update()
    {
        counter.text = countdown.ToString();
        counter2.text = countdown.ToString();

    }

    public override IEnumerator OnEnvironmentTurn(PlayerData[] allPlayers)
    {
        if (countdown > 0)
        {
            countdown--;

            isFinished = true;
            yield break;
        }

        countdown = countdowntimer;

        Vector3 bulletPosition;
        Character[] hitPlayers = getHitPlayers(out bulletPosition);

        foreach (Character player in hitPlayers)
        {
            Vector3 moveToPosition = player.CurrentBlock.position + transform.forward;
            Block moveToBlock = Block.GetOrCreateBlockAtPosition(moveToPosition, 1, ~0);

            StartCoroutine(player.MoveToBlock(moveToBlock, Character.Animation.Hit, 1));
        }


        StartCoroutine(lerpShot(bulletPosition, Vector3.Distance(spawnLocation.position,bulletPosition)/15));

        if (hitPlayers.Length > 0)
            yield return new WaitForSeconds(1.5f);
        
        isFinished = true;
        yield break;
    }


    private Character[] getHitPlayers(out Vector3 endPosition)
    {

        Vector3 curPos;       
        List<Character> retVal = new List<Character>();
        Block hit;
        endPosition = position + Vector3.up;

        for (int i = 1; i < 50; i++)
        {

            curPos = position + (transform.forward * i);
            endPosition = curPos + Vector3.one; //position which bullet will stop at

            if (Block.isBlockAtPosition(curPos, 1, ~0, out hit))
            {
                if (hit.CurrentPlayer != null)
                    retVal.Add(hit.CurrentPlayer);
            }

            //this will stop the bullet
            if (Block.isBlockAtPosition(curPos + Vector3.up, 1, ~0))
                break;

        }//end forloop
        return retVal.ToArray();
    }

    private IEnumerator lerpShot(Vector3 endPosition, float time)
    {
        GameObject shot = Instantiate(shootingObject, spawnLocation.position, spawnLocation.rotation);
        Vector3 startPosition = spawnLocation.position;
        float elapsedTime = 0;

        while(elapsedTime < time)
        {

            shot.transform.position = Vector3.Lerp(startPosition, endPosition, elapsedTime / time);

            yield return new WaitForEndOfFrame();
            elapsedTime += Time.deltaTime;
        }

        //reset
        Destroy(shot);
    }
}