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

public class NoiseGenerator
{
    public void applyTileNoise(GameObject tile)
    {
        Mesh mesh = tile.GetComponent<MeshFilter>().mesh;
        Vector3[] vertices = mesh.vertices;
        float[] samples = calculateSamples(tile);
        for (int i = 0; i < samples.Length; i++)
        {
            vertices[i].y = samples[i] * 5;
        }
        applyMesh(tile, vertices, mesh);
    }

    public void applyStoneTileNoise(GameObject tile)
    {
        Mesh mesh = tile.GetComponent<MeshFilter>().mesh;
        Vector3[] vertices = mesh.vertices;
        float[] samples = calculateSamples(tile);
        for (int i = 0; i < samples.Length; i++)
        {
            vertices[i].y = samples[i] * 10;
        }
        applyMesh(tile, vertices, mesh);
    }

    public void applyTreeTileNoise(GameObject tile)
    {
        Mesh mesh = tile.GetComponent<MeshFilter>().mesh;
        Vector3[] vertices = mesh.vertices;
        float[] samples = calculateSamples(tile);
        for (int i = 0; i < samples.Length; i++)
        {
            vertices[i].y = samples[i] * 7.5f;
        }
        applyMesh(tile, vertices, mesh);
    }

    public void applyCityTileNoise(GameObject tile)
    {
        //Currently no noise. (Objects floating)
    }

    private float[] calculateSamples(GameObject tile)
    {
        Mesh mesh = tile.GetComponent<MeshFilter>().mesh;
        Vector3[] vertices = mesh.vertices;
        float[] samples = new float[vertices.Length - 1];
        for (int i = 0; i < vertices.Length; i++)
        {
            if (vertices[i].x != 5 && vertices[i].z != 5 && vertices[i].x != -5 && vertices[i].z != -5)
            {
                float xCord = tile.GetComponent<Tile>().getPosition().x + vertices[i].x / (vertices.Length - 1) * 10;
                float yCord = tile.GetComponent<Tile>().getPosition().z + vertices[i].z / (vertices.Length - 1) * 10;
                float sample = Mathf.PerlinNoise(xCord, yCord) - 0.5f;
                samples[i] = sample;
            }
        }
        return samples;
    }

    private void applyMesh(GameObject tile, Vector3[] vertices, Mesh mesh)
    {
        mesh.vertices = vertices;
        mesh.RecalculateBounds();
        mesh.RecalculateNormals();
        tile.GetComponent<MeshCollider>().sharedMesh = mesh;
    }
}
