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

public class CubeSpawn : MonoBehaviour
{
    float timeUntil_difficulty = 0.1f;
    public float difficulty = 0.015f;

    bool gameOver;
    float gameTime;
    float timeUntilNextCube;

    StillHaveCubes cubecount;

    // Start is called before the first frame update
    void Start()
    {
        gameOver = false;
        cubecount = (StillHaveCubes)FindObjectOfType(typeof(StillHaveCubes));
        gameTime = 0;
        SpawnACube();
        timeUntilNextCube = 5;
    }

    // Update is called once per frame
    void Update()
    {
        if (cubecount.cubeCount == 0 && Time.timeSinceLevelLoad > 1.0f)
        {
            gameOver = true;
        }
        if (gameOver) return;

        gameTime += Time.deltaTime;

        float tilt = 1.0f - Vector3.Dot(cubecount.transform.up.normalized, Vector3.up);

        /*
        float modifiedDifficulty = difficulty * Mathf.Log(gameTime) * (1 / Mathf.Max(Mathf.Sqrt(tilt), 0.1f));

        if (Random.value < Time.deltaTime * modifiedDifficulty)
        {
            SpawnACube();
        }
        */

        timeUntilNextCube -= Time.deltaTime;

        if (timeUntilNextCube < 0)
        {
            if (Random.value > Mathf.Sqrt(tilt))
            {
                SpawnACube();
            }
            timeUntilNextCube = (50.0f * Random.Range(0.25f, 1.75f) * Mathf.Max(Mathf.Sqrt(tilt), 0.15f)) / (Mathf.Log(gameTime));
            Debug.Log(timeUntilNextCube);
            if (timeUntilNextCube > 5.0f) 
            {
                timeUntilNextCube = 4.5f + Random.value; 
            }
        }
    }

    void SpawnACube()
    {
        if (gameOver) return;
        Instantiate(Resources.Load("Cube"), new Vector3(Random.Range(-3.5f, 3.5f), 15, Random.Range(-3.5f, 3.5f)), Quaternion.identity);
    }

    public bool IsGameOver()
    {
        return gameOver;
    }

    public float GameTime()
    {
        return gameTime;
    }

    public virtual void OnTriggerEnter(Collider other)
    {
        if (gameOver) return;
        other.transform.position = new Vector3(Random.Range(-4.5f, 4.5f), 15, Random.Range(-4.5f, 4.5f));
        other.transform.GetComponent<Rigidbody>().velocity = Vector3.zero;
    }
}
