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

public class CatCannonC : MonoBehaviour
{
    [SerializeField] private GameObject catPrefab = null;
    [SerializeField] private Transform spawnPoint = null;
    [SerializeField] private Transform barrel = null;
    [SerializeField] private float despawnRange = 20f;
    [SerializeField] private float minForce = 1300f;
    [SerializeField] private float maxForce = 1500f;
    [SerializeField] private float interval = 15f;
    [SerializeField] private float minInterval = 5;

    private CatC cat;
    private float despawnMagnitude;
    private float timestamp;
    private AudioSource audio;

    // Start is called before the first frame update
    void Awake()
    {
        this.audio = this.GetComponent<AudioSource>();

        GameObject catObject = Instantiate(this.catPrefab, this.spawnPoint);
        this.cat = catObject.GetComponent<CatC>();
        this.cat.Initialize();

        this.despawnMagnitude = this.despawnRange * this.despawnRange;
        this.timestamp = Time.timeSinceLevelLoad + this.interval * (0.5f + UnityEngine.Random.value);

        Debug.Log(this.timestamp);
    }

    // Update is called once per frame
    void Update()
    {
        this.TryCatchCat();
        this.TryTrigger();
    }

    private void TryTrigger()
    {
        if (Time.timeSinceLevelLoad < this.timestamp)
        {
            return;
        }

        this.timestamp = Time.timeSinceLevelLoad + this.interval * (0.5f + UnityEngine.Random.value);

        this.TryShoot();
    }

    private void TryShoot()
    {
        if (this.cat.Simulated)
        {
            return;
        }

        this.Shoot();
    }

    private void Shoot()
    {
        this.cat.BlowAway(this.barrel.rotation * Vector2.right * UnityEngine.Random.Range(this.minForce, this.maxForce) / 50f);
        this.interval = Math.Max(this.minInterval, this.interval - 1);
        this.audio.pitch = 0.9f + 0.2f * UnityEngine.Random.value;
        this.audio.PlayOneShot(this.audio.clip);
    }

    private void TryCatchCat()
    {
        if (!this.cat.Simulated)
        {
            this.cat.transform.position = this.transform.position;
            return;
        }

        if ((this.transform.position - this.cat.transform.position).sqrMagnitude < this.despawnMagnitude)
        {
            return;
        }

        this.cat.Reset(this.transform);
    }
}
