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

public class ClownC : MonoBehaviour
{
    [SerializeField] private Sprite waiting = null;
    [SerializeField] private Sprite free = null;
    [SerializeField] private GameObject secret = null;
    [SerializeField] private float riceSpeed = 1.0f;
    [SerializeField] private float maxAltidude = 15f;
    [SerializeField] private float minSkip = 8f;
    [SerializeField] private float maxSkip = 10f;

    private Rigidbody2D body;
    private SpriteRenderer spriteRenderer;
    private AudioSource audio;

    // Start is called before the first frame update
    void Awake()
    {
        this.Initialize();   
    }

    public void Initialize()
    {
        this.audio = this.GetComponent<AudioSource>();
        this.body = this.GetComponent<Rigidbody2D>();
        this.spriteRenderer = this.GetComponent<SpriteRenderer>();
    }

    public void Free()
    {
        this.spriteRenderer.sprite = this.free;
        this.spriteRenderer.flipX = false;
        this.secret.SetActive(true);
        this.audio.pitch = 0.9f + 0.2f * UnityEngine.Random.value;
        this.audio.Play();
    }

    public void Reset()
    {
        this.spriteRenderer.sprite = this.waiting;
        this.spriteRenderer.flipX = true;
        this.secret.SetActive(false);

        Vector3 position = this.transform.position;
        position.x += UnityEngine.Random.Range(this.minSkip, this.maxSkip);
        position.y = 0f;
        this.transform.position = position;
    }

    void Update()
    {
        this.Tick();
    }

    private void Tick()
    {
        if (!this.secret.activeSelf)
        {
            return;
        }

        Vector3 position = this.transform.position;

        if (this.maxAltidude < position.y)
        {
            this.Reset();
            return;
        }

        position.y += Time.deltaTime * this.riceSpeed;

        this.transform.position = position;
    }

}
