using JigLibX.Collision;
using JigLibX.Geometry;
using JigLibX.Physics;
using JigLibX.Utils;
using Microsoft.Xna.Framework;

namespace Innovation
{
    public class HeightMapObject : PhysicsObject
    {
        public HeightMapInfo info;

        public HeightMapObject(HeightMapInfo heightMapInfo, Vector2 shift)
        {
            Setup(heightMapInfo, shift);
            InitializeComponent(Engine.DefaultScreen);
            this.Serialize = false;
        }

        public HeightMapObject(HeightMapInfo heightMapInfo, Vector2 shift, GameScreen parent)
        {
            Setup(heightMapInfo, shift);
            InitializeComponent(parent);
            this.Serialize = false;
        }

        void Setup(HeightMapInfo heightMapInfo, Vector2 shift)
        {
            Body = new Body(); // just a dummy. The PhysicObject uses its position to get the draw pos
            CollisionSkin = new CollisionSkin(null);

            info = heightMapInfo;
            Array2D field = new Array2D(heightMapInfo.Heights.GetUpperBound(0), heightMapInfo.Heights.GetUpperBound(1));

            for (int x = 0; x < heightMapInfo.Heights.GetUpperBound(0); x++)
            {
                for (int z = 0; z < heightMapInfo.Heights.GetUpperBound(1); z++)
                {
                    field.SetAt(x, z, heightMapInfo.Heights[x, z]);
                }
            }

            // move the body. The body (because its not connected to the collision
            // skin) is just a dummy. But the base class should know where to
            // draw the model.
            Body.MoveTo(new Vector3(shift.X, 0, shift.Y), Matrix.Identity);

            CollisionSkin.AddPrimitive(new Heightmap(field, shift.X, shift.Y, 1, 1), (int)MaterialTable.MaterialID.UserDefined, new MaterialProperties(0.7f, 0.7f, 0.6f));

            PhysicsSystem.CurrentPhysicsSystem.CollisionSystem.AddCollisionSkin(CollisionSkin);
        }
    }
}
