using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace DXGfxLib.Serialization
{
    public class TerrainSurrogate : ISerializationSurrogate
    {
        /// <summary>
        /// This is called to serialize the Scene.
        /// </summary>
        /// <param name="obj">The scene object that need to be serialized.</param>
        /// <param name="info">where we have to write what we want to be serialized.</param>
        /// <param name="context"></param>
        public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context)
        {
            if (obj == null)
            {
                throw new NullReferenceException("No scene object to serialize, this is wrong!");
            }

            Terrain terrain = obj as Terrain;

            if (terrain == null)
            {
                throw new ArgumentException("The Object passed through obj argument is not a scene object, this is wrong!");
            }

            info.AddValue("HeightMap", terrain.heightmapFile, typeof(string));
            info.AddValue("BaseTexture", terrain.baseTextureFile, typeof(string));
            info.AddValue("SecondTexture", terrain.secondTextureFile, typeof(string));
            info.AddValue("SecondTextureHeight", terrain.secondTexHeigth, typeof(float));
        }

        /// <summary>
        /// This is called to deserialize a scene object.
        /// </summary>
        /// <param name="obj">The scene object we need to populate with values.</param>
        /// <param name="info">Serialized information we need to read and push to the scene object.</param>
        /// <param name="context"></param>
        /// <param name="selector"></param>
        /// <returns>null (ignored)</returns>
        public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
        {
            if (obj == null)
            {
                throw new NullReferenceException("No scene object to serialize, this is wrong!");
            }

            Terrain terrain = obj as Terrain;

            if (terrain == null)
            {
                throw new ArgumentException("The Object passed through obj argument is not a terrain object, this is wrong!");
            }

            terrain.Initialize();
            terrain.heightmapFile = (string)info.GetValue("HeightMap", typeof(string));
            terrain.baseTextureFile = (string)info.GetValue("BaseTexture", typeof(string));
            terrain.secondTextureFile = (string)info.GetValue("SecondTexture", typeof(string));
            terrain.secondTexHeigth = (float)info.GetValue("SecondTextureHeight", typeof(float));

            return null;
        }
    }
}
