using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using DG.Tweening;
using UnityEngine;

public class kebabthrow : MonoBehaviour
{
    public GameObject stonePrefab;
    public GameObject Marti;

    public Transform initialStonePosition;
    public Transform pathParent;

    private bool canThrow = true;
    private Vector3[] pathArray;
    private void Start()
    {
        pathArray = new Vector3[pathParent.childCount + 1];
        for (int i = 0; i < pathArray.Length - 1; i++)
        {
            pathArray[i] = pathParent.GetChild(i).position;
        }
        pathArray[pathArray.Length - 1] = pathArray[0];
        StartMoving();
    }

    private void StartMoving()
    {
        transform.DOPath(pathArray, 10f).SetLookAt(0.01f).SetLoops(-1, LoopType.Restart).SetEase(Ease.Linear);
    }

    private void Update()
    {
        Vector3 direction = Marti.transform.position - transform.position;
        if (direction.magnitude < 15f && canThrow)
        {
            ThrowStone();
        }
        else if (!canThrow)
        {
            // turn your face to Marti
            transform.LookAt(Marti.transform);
        }
    }

    public async void ThrowStone()
    {
        canThrow = false;

        GetComponent<Animator>().SetTrigger("Throw");

        // stop the movement
        transform.DOKill();

        GameObject stoneInstance = Instantiate(stonePrefab, initialStonePosition.position, Quaternion.identity);
        stoneInstance.transform.parent = initialStonePosition;

        await Task.Delay(2100);

        stoneInstance.transform.parent = null;

        var stone_rb = stoneInstance.AddComponent<Rigidbody>();
        stone_rb.useGravity = false;
        Vector3 direction = Marti.transform.position - stoneInstance.transform.position;
        stone_rb.AddForce(direction.normalized * 1000f);

        Destroy(stoneInstance, 3f);

        StartCoroutine(WaitForXAndDisable());
    }

    private IEnumerator WaitForXAndDisable()
    {
        yield return new WaitForSeconds(4f);
        canThrow = true;
        StartMoving();
    }
}
