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

public class TomatoScript : MonoBehaviour
{
    public Transform player;
    [Range(1f,100f)]public float damage;

    public AudioClip launchSound, splashSound, freddieCry;


    void Start()
    {
        player = GameObject.Find("CHARACTER").transform;
        Vector3 directionTir = ((player.position +Vector3.up*0.5f)- transform.position).normalized;
        GetComponent<Rigidbody>().AddForce(directionTir*12f + Vector3.up*3f,ForceMode.VelocityChange);
        if (launchSound) AudioSource.PlayClipAtPoint(launchSound, Camera.main.transform.position);
    }

    void OnTriggerEnter(Collider objetTouche)
    {
        if (objetTouche.tag == "SceneFloor")
        {
            CrashOnFloor();
        }
        if (objetTouche.tag == "Player")
        {
            SplashFace();
        }
    }

    void CrashOnFloor()
    {
        if (splashSound) AudioSource.PlayClipAtPoint(splashSound, Camera.main.transform.position);

        Vector3 newPos = transform.position;
        newPos.y = -0.95f;
        transform.position = newPos;
        GetComponent<Rigidbody>().useGravity = false;
        GetComponent<Rigidbody>().velocity = Vector3.zero;
        transform.GetChild(0).gameObject.SetActive(false);
        transform.GetChild(1).gameObject.SetActive(true);
        GetComponent<SphereCollider>().enabled = false;
    }

    void SplashFace()
    {
        if (splashSound) AudioSource.PlayClipAtPoint(splashSound, Camera.main.transform.position);
        if (freddieCry) AudioSource.PlayClipAtPoint(freddieCry, Camera.main.transform.position);
        player.SendMessage("AddScore", -damage, SendMessageOptions.DontRequireReceiver);
        GetComponent<SphereCollider>().enabled = false;

        transform.parent = player;
        transform.localPosition = new Vector3(0, 0.6f, -0.1f);
        transform.GetChild(0).gameObject.SetActive(false);
        transform.GetChild(1).gameObject.SetActive(true);
        transform.GetChild(1).Rotate(transform.right, 90f);
        GetComponent<Rigidbody>().useGravity = false;
        GetComponent<Rigidbody>().velocity = Vector3.zero;
        StartCoroutine(Shrink());
    }

    IEnumerator Shrink()
    {
        yield return new WaitForSeconds(1f);

        while (transform.localScale.x > 0.05f)
        {
            transform.localScale *= 0.95f;
            yield return null;
        }
        Destroy(gameObject);
    }


}
