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

public class Bubble : MonoBehaviour
{
    public float size;
    public float levitateSpeed;
    
    public float elapsedTime, lifeTime;
    public float expansionRate;
    public float bubbleForceCoefficient;
    public float bubbleAcceleration;
    public float maxLevitationSpeed;
    
    public BubbleManager bubbleManager;

    public Vector3 velocity;
    public float bubbleFriction; // !!! only used to decrease the initial velocity inherited from the player
    public float inheritedVelocityCoefficient;

    public AudioSource audioSource;

    public float minBubbleSizeForJump; // to prevent the player from being able to fly

    // bubble dynamics 101:
    /****
     * bubbles get larger as they move upwards due to decreasing pressure
     * bubbles speed up as they move upwards? skip for game and have brief initial acceleration period before max velocity to ease movement
     * 
     * bubbles have a velocity (to allow for wind to be added in later stages of the game)
     * 
     * 
     * 
     * 
     */

    bool destroyed;
    public void Pop()
    {
        destroyed = true;
        // play pop animation...
        audioSource.Play();
        
        // remove self from bubbleManager list:
        bubbleManager.bubbles.Remove(this);


        //Debug.Log("pop!");
        
    }
    
    private void Start()
    {
        transform.localScale = Vector3.one * size; // default mesh is a sphere of radius 1 unit
        velocity *= inheritedVelocityCoefficient;
    }

    public float getBubbleForceMultipler() // bigger bubbles give more height when the player impacts them
    {
        if (size < minBubbleSizeForJump)
        {
            return 0.0f;
        }
        else
        {
            return bubbleForceCoefficient * size;
        }

        
    }


    
    private void Update()
    {
        



        elapsedTime += Time.deltaTime;

        if (elapsedTime >= lifeTime && !destroyed)
        {
            //Debug.Log("bubble lifetime surpassed");
            Pop();
        }


        if (destroyed && !audioSource.isPlaying)
        {
            Destroy(gameObject);
        }

        velocity -= velocity * bubbleFriction * Time.deltaTime;

        size += expansionRate * Time.deltaTime;

        levitateSpeed += bubbleAcceleration * Time.deltaTime;
        levitateSpeed = Mathf.Clamp(levitateSpeed, 0.0f, maxLevitationSpeed);

        transform.localScale = Vector3.one * size;
        transform.position += Vector3.up * levitateSpeed * Time.deltaTime;

        transform.position += velocity * Time.deltaTime; // transform by inherited velocity;
    }
}
