using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Networking.Client;

public class FloatingOnWater : MonoBehaviour
{
    bool characterInWater = false;
    public ConnectedClients clientData;
    private List<string> Names;
    public GameObject lilypad;
    GameObject player;
    string charName;

    private void Start()
    {
      for(int i = 0; i < clientData.AllClients.Count; i++)
        {
            Names.Add(clientData.AllClients[i].characterAnimal + "(Clone)");
        }
    }
    void OnTriggerEnter(Collider other)
    {
        for(int i = 0; i < Names.Count; i++)
        {
            if (other.gameObject.name == Names[i])
            {
                characterInWater = true;
                charName = other.gameObject.name;
            }
        }
    }

    IEnumerator FloatSinkCoroutine(Vector3 endPosition)
    {
        float elapsedTime = 0;
        Vector3 startPosition = lilypad.transform.position;
        Vector3 charStartPosition = player.transform.position;
        Vector3 charEndPosition = new Vector3(player.transform.position.x, 1, player.transform.position.z);
        float time = 0.8f;
        while (elapsedTime < time)
        {
            lilypad.transform.position = Vector3.Lerp(startPosition, endPosition, (elapsedTime / time));
            player.transform.position = Vector3.Lerp(charStartPosition, charEndPosition, (elapsedTime / time));
            yield return new WaitForEndOfFrame();
            elapsedTime += Time.deltaTime;
        }
        player.transform.position = charEndPosition;
        lilypad.transform.position = endPosition;
    }

    public void Animate()
    {
        if(characterInWater == true)
        {
            player = GameObject.Find(charName);
            StartCoroutine(FloatSinkCoroutine(new Vector3(0, 1, 0)));
        }
    }
    public void returnToPosition()
    {
        StartCoroutine(FloatSinkCoroutine(new Vector3(0, 0, 0)));
    }
}
