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

public class FloatingOnWater : MonoBehaviour
{
    bool characterInWater = true;
    public ClientList clientData;
    public List<string> Names = new List<string>();
    public GameObject lilypad;
    GameObject player;
    string charName;
    public bool triggeranimate;
    public bool triggeranimate1;

    private void Update()
    {

    }

    private void Start()
    {
      for(int i = 0; i < clientData.ConnectedClients.Count; i++)
        {
            Names.Add(clientData.ConnectedClients[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 FloatCoroutine()
    {
        float elapsedTime = 0;
        Vector3 startPosition = lilypad.transform.position;
        Vector3 endPosition = new Vector3(lilypad.transform.position.x, lilypad.transform.position.y + 1.0f, lilypad.transform.position.z);
        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;
    }
    IEnumerator SinkCoroutine()
    {
        float elapsedTime = 0;
        Vector3 startPosition = lilypad.transform.position;
        Vector3 endPosition = new Vector3(lilypad.transform.position.x, lilypad.transform.position.y - 1.0f, lilypad.transform.position.z);
        float time = 0.8f;
        while (elapsedTime < time)
        {
            lilypad.transform.position = Vector3.Lerp(startPosition, endPosition, (elapsedTime / time));
            yield return new WaitForEndOfFrame();
            elapsedTime += Time.deltaTime;
        }
        lilypad.transform.position = endPosition;
    }

    public void Animate()
    {
        if(characterInWater == true)
        {
            player = GameObject.Find(charName);
            StartCoroutine(FloatCoroutine());
        }
    }
    public void returnToPosition()
    {
        StartCoroutine(SinkCoroutine());
    }
}
