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

public class GenerateHeightMap : MonoBehaviour
{
    float[,] map;
    [SerializeField]
    [Range(10, 100)]
    int mapHeight, mapWidth;

    [SerializeField]
    [Range(0, 100)]
    float blockSize, blockHeight, frequency, scale;
    public GameObject minecraftBlock, objectToCollect;
    // Start is called before the first frame update
    void Start()
    {
        map = new float[mapWidth, mapHeight];
        minecraftBlock.transform.localScale = new Vector3(blockSize, blockHeight, blockSize);
        initArray();
        displayArray();
        AddObjects();
        AddPlayer();

    }

    void AddPlayer()
    {

        GameObject.Find("Player").transform.position = new Vector3(Random.Range(0, mapWidth), 30, Random.Range(0, mapHeight));

    }
    void AddObjects()
    {
        
        GameObject object1 = (GameObject)(Instantiate(objectToCollect, new Vector3(Random.Range(0,mapWidth), 150, Random.Range(0, mapHeight)), Quaternion.identity));
        object1.GetComponent<ObjectToBeCollected>().type = Item.ItemType.RED_DIAMOND;
        object1.AddComponent<Rigidbody>();
        object1.GetComponent<Rigidbody>().collisionDetectionMode = CollisionDetectionMode.Continuous;
        object1.name = "Red Diamond";

        GameObject object2 = (GameObject)(Instantiate(objectToCollect, new Vector3(Random.Range(0, mapWidth), 150, Random.Range(0, mapHeight)), Quaternion.identity));
        object2.GetComponent<ObjectToBeCollected>().type = Item.ItemType.BLUE_DIAMOND;
        object2.AddComponent<Rigidbody>();
        object2.GetComponent<Rigidbody>().collisionDetectionMode = CollisionDetectionMode.Continuous;
        object2.name = "Blue Diamond";




    }

    void initArray()
    {

        map = new float[mapWidth, mapHeight];

        for (int j = 0; j < mapHeight; j++)
        {
            for (int i = 0; i < mapWidth; i++)
            {

                float nx = i / mapWidth;
                float ny = j / mapHeight;
                map[i, j] = Mathf.PerlinNoise(i * 1.0f / frequency + 0.1f, j * 1.0f / frequency + 0.1f);
            }

        }


    }

    void displayArray()
    {
        for (int j = 0; j < mapHeight; j++)
        {
            for (int i = 0; i < mapWidth; i++)
            {
                GameObject t = (GameObject)(Instantiate(minecraftBlock, new Vector3(i * blockSize, Mathf.Round(map[i, j] * blockHeight * scale), j * blockSize), Quaternion.identity));
                t.transform.SetParent(gameObject.transform);
            }
        }

    }



    // Update is called once per frame
    void Update()
    {
        
    }
}
