using Unity.VisualScripting;
using UnityEngine;

public class KontraktionBeiZusammenstoss : MonoBehaviour
{
    public float hardness;
    private Vector2 originalScale;
    private float originalArea;
    private float originalSizeY;
    private float velocity;
    private bool ongoingAnimation;
    private SpriteRenderer spriteRenderer;
    private Rigidbody2D rigidBody;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        ongoingAnimation = false;
        velocity = 0;
        spriteRenderer = GetComponent<SpriteRenderer>();
        rigidBody = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (ongoingAnimation){
            float indent = (originalScale.y - transform.localScale.y) / originalScale.y * originalSizeY;
            if (indent < 0) {
                // one period completed, end animation
                ongoingAnimation = false;
                velocity = 0;
                transform.localScale = originalScale;
            } else {
                float backwardsForce = indent * hardness;
                velocity -= backwardsForce * Time.deltaTime;
                float yScale = transform.localScale.y - velocity * Time.deltaTime / originalSizeY * originalScale.y;
                float xScale = originalArea / yScale;
                transform.localScale = new Vector3(xScale, yScale, transform.localScale.z);
                transform.position += Vector3.down * velocity * Time.deltaTime;
            }
        } else {
            velocity = - rigidBody.linearVelocityY;
        }
    }

    void OnCollisionEnter2D(Collision2D collision) {
        if (!ongoingAnimation){
            ContactPoint2D[] contacts = new ContactPoint2D[collision.contactCount];
            collision.GetContacts(contacts);
            originalScale = transform.localScale;
            originalArea = originalScale.x * originalScale.y;
            originalSizeY = spriteRenderer.bounds.size.y;
            ongoingAnimation = true;
        }
    }
}
