using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using VisiMath;

namespace VisimBox.Physics
{
    public class PhysMaterial : IXmlSerializable
    {
        float _Dynamic;
        float _Static;
        float _Rest;

        
        /// <summary>
        /// Dynamic friction of the material (when object moves)
        /// </summary>
        public float DynamicFriction { get { return _Dynamic; } set { _Dynamic = MathTools.Clamp(value, 0, 1); } }

        /// <summary>
        /// Static friction of the material (when object rests on another)
        /// </summary>
        public float StaticFriction { get { return _Static; } set { _Static = MathTools.Clamp(value, 0, 1); } }
        
        /// <summary>
        /// Restitution - bouncines of the material
        /// </summary>
        public float Restitution { get { return _Rest; } set { _Rest = MathTools.Clamp(value, 0, 1); } }

        public PhysMaterial()
        {
            DynamicFriction = StaticFriction = Restitution = 0.5f;
        }

        public PhysMaterial(float dynafr, float statfr, float rest)
        {
            DynamicFriction = dynafr;
            StaticFriction = statfr;
            Restitution = rest;
        }

        public PhysMaterial(XmlReader reader)
        {
            ReadXml(reader);
        }

        public PhysMaterial(PhysMaterial mat)
        {
            DynamicFriction = mat.DynamicFriction;
            StaticFriction = mat.StaticFriction;
            Restitution = mat.Restitution;
        }

        #region IXmlSerializable Members

        /// <summary>
        /// Reqired by IXMLserializable
        /// </summary>
        /// <returns>Null</returns>
        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        /// <summary>
        /// Deserializes object from XML
        /// </summary>
        /// <param name="reader">XML reader</param>
        public void ReadXml(XmlReader reader)
        {
            _Dynamic = XMLHelper.FloatFromString(reader["DynamicFriction"]);
            _Static= XMLHelper.FloatFromString(reader["StaticFriction"]);
            _Rest= XMLHelper.FloatFromString(reader["Restitution"]);
        }

        /// <summary>
        /// Serializes object to XML
        /// </summary>
        /// <param name="writer">XML writer to save values</param>
        public void WriteXml(XmlWriter writer)
        {
            XMLHelper.WriteFloatAttribute(writer, "DynamicFriction", DynamicFriction);
            XMLHelper.WriteFloatAttribute(writer, "StaticFriction", StaticFriction);
            XMLHelper.WriteFloatAttribute(writer, "Restitution", Restitution);
        }

        public void WriteXml(XmlWriter writer, string RootNode)
        {
            writer.WriteStartElement(RootNode);
            WriteXml(writer);
            writer.WriteEndElement();
        }

        #endregion
    }
}
