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

namespace Innovation
{
    // A capsule physics simulation object
    public class CapsuleObject : PhysicsObject
    {
        // Radius of capsule
        public float Radius
        {
            get { return ((Capsule)CollisionSkin.GetPrimitiveLocal(0)).Radius; }
            set { SetupSkin(Length, value); }
        }

        // Length of capsule
        public float Length
        {
            get { return ((Capsule)CollisionSkin.GetPrimitiveLocal(0)).Length; }
            set { SetupSkin(value, Radius); }
        }

        // Constructors

        public CapsuleObject() : base()
        {
            InitializeBody();
            SetupSkin(3, 1);
        }

        public CapsuleObject(float Length, float Radius)
        {
            InitializeBody();
            SetupSkin(Length, Radius);
        }

        public CapsuleObject(float Length, float Radius, Vector3 Position, 
            Vector3 Rotation) : base()
        {
            InitializeBody();
            SetupSkin(Length, Radius);
            this.Position = Position;
            this.EulerRotation = Rotation;
        }

        // Sets up the collision skin
        void SetupSkin(float Length, float Radius)
        {
            // Update the collision skin
            CollisionSkin.RemoveAllPrimitives();
            CollisionSkin.AddPrimitive(new Capsule(
                Vector3.Transform(new Vector3(-0.5f, 0, 0), Rotation), 
                Rotation, Radius, Length), 
                (int)MaterialTable.MaterialID.UserDefined, 
                PhysicsMaterial);
        }

        public override void SaveSerializationData(SerializationData Data)
        {
            base.SaveSerializationData(Data);
            
            Data.AddData("CapsuleObject.Length", this.Length);
            Data.AddData("CapsuleObject.Radius", this.Radius);
        }

        public override void LoadFromSerializationData(SerializationData Data)
        {
            base.LoadFromSerializationData(Data);

            this.Length = Data.GetData<float>("CapsuleObject.Length");
            this.Radius = Data.GetData<float>("CapsuleObject.Radius");
        }
    }
}