using System;
using ComponentFramework.Modules;
using ComponentFramework;

namespace OctreeRendering
{
    [AutoLoad]
    class WorldBuilder : Component
    {
        const int WorldSize = 64;
        //const int WorldSize = 4;
        const int WaterLevel = WorldSize / 3;
        //const int WaterLevel = WorldSize;

        public WorldBuilder(ICore core) : base(core) { }

        public override void Initialize()
        {
            WorldState.TotalInstances = 0;
            WorldState.Octree.Size = WorldSize;

            const float halfWorldSize = WorldSize / 2f;

            for (int i = 0; i < WorldSize; i++)
            for (int j = 0; j < WaterLevel; j++)
            for (int k = 0; k < WorldSize; k++)
            {
                var p = (float)j / WaterLevel + (1 - new Vector2f(i - halfWorldSize, k - halfWorldSize).Length() / halfWorldSize);
                //var p = 1;

                if (RandomHelper.Probability(Math.Sqrt(p)))
                {
                    var tile = new TileInfo 
                    { 
                        Phi = RandomHelper.Random.Next(-1, 3) * MathHelper.HalfPi,
                        Type = (j == WaterLevel-1) ? TileType.GrassTop : RandomHelper.Probability((float)j / WaterLevel) ? TileType.LightRock : TileType.DarkRock
                    };
                    WorldState.Octree.Fill(new Vector3i(i, j, k), tile);
                    WorldState.TotalInstances++;
                }
            }

            WorldState.OnWorldRebuilt();
        }

        [ServiceDependency]
        public IWorldState WorldState { private get; set; }
    }
}
