using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using uTools;

public class Soul : MonoBehaviour
{
    public Rigidbody rb;
    public bool collected = false;
    public float lerpValue = 0.05f;
    public int addMp = 10;
    public uTweenPositionTarget tweenPos;
    public float flySpeed = 10f;
    public float upSpeed = 1;
    public float shootSpeed;
    public float altitude;
    [HideInInspector]
    public bool isShoot;
    [HideInInspector]
    public Vector3 from;
    [HideInInspector]
    public Vector3 to;
    [HideInInspector]
    public float time;

    private void Awake()
    {
        SoulInMap.souls.Add(this);
    }
    public void Burst(Vector3 velocity)
    {
        rb.isKinematic = false;
        rb.velocity = velocity;
        collected = false;
    }

    public async void BeCollect(int id)
    {
        rb.isKinematic = true;
        collected = true;
        tweenPos.from = transform;
        tweenPos.to = PlayersInput.instance[id].transform;
        tweenPos.duration = (tweenPos.from.position - tweenPos.to.position).magnitude / flySpeed;
        tweenPos.ResetToBeginning();
        tweenPos.PlayForward();
        await Task.Delay((int)(tweenPos.duration * 1000));
        BeGet(id);
        SoulInMap.souls.Remove(this);
        gameObject.SetActive(false);
    }

    public void BeGet(int id)
    {
        PlayersInput.instance[id].mp += addMp;
    }

    private void FixedUpdate()
    {
        if (isShoot)
        {
            time += Time.deltaTime;
            transform.position = Vector3.Lerp(from, to, time);
            if (Vector3.Distance(transform.position, to)<1f)
            {
                isShoot = false;
            }
        }   
        if(transform.position.y>= altitude)
        {
            rb.velocity = Vector3.zero;
        }
        else
        {
            Vector3 velocity = rb.velocity;
            velocity.y = upSpeed;
            rb.velocity = velocity;

        }
    }
    public void BeShoot()
    {
        time = 0;
        isShoot = true;
    }
}
