using UnityEngine;

namespace Assets.Common
{
    public class PerlinNoiseGenerator
    {
        public float Scale { get; set; } = 0.001f;
        public Point Offset { get; set; } = new Point(0, 0);
        public int Iterations { get; set; } = 8;
        public float Decay { get; set; } = .7f;
        public float Lacunarity { get; set; } = 1.71f;

        public double GetValue(Point position)
        {
            var amplitude = 1.0;
            var scale     = Scale;
            var result    = 0.0;

            for (int i = 0; i < Iterations; i++) {
                result += amplitude * Calculate(position, scale);

                amplitude *= Decay;
                scale     *= Lacunarity;
            }

            return Mathf.InverseLerp(0.38f, 0.48f, (float)(result / ((1 - System.Math.Pow(Decay, Iterations)) / (1 - Decay))));
        }

        private double Calculate(Point position, float scale)
        {
            var final = (position + Offset) * scale;

            return Mathf.PerlinNoise((float)final.x, (float)final.y);
        }
    }
}