using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace YourBeatingHeart.Main.Helper
{
    public class SerializationHelper
    {
        public static bool SerializeObject(string filename, ISerializable objectToSerialize)
        {
            Stream stream = null;
            try
            {
                // Open a stream and try to write the object
                stream = File.Open(filename, FileMode.Create);
                BinaryFormatter bFormatter = new BinaryFormatter();
                bFormatter.Serialize(stream, objectToSerialize);
                return true;
            }
            catch (IOException e)
            {
                // If we are debugging, throw the exception on, if not just omit it
                if (Constants.DEBUG)
                {
                    throw e;
                }
            }
            finally
            {
                // Finally close the stream
                try
                {
                    if (stream != null)
                        stream.Close();
                }
                catch
                {
                }
            }

            return false;
        }

        public static ISerializable DeserializeObject(string filename)
        {
            Stream stream = null;
            try
            {
                // Open a stream and try to read the object
                stream = File.Open(filename, FileMode.Open);
                BinaryFormatter bFormatter = new BinaryFormatter();
                ISerializable resultingObject = (ISerializable)bFormatter.Deserialize(stream);
                return resultingObject;
            }
            catch (Exception e)
            {
                // Exception? Throw on.
                throw e;
            }
            finally
            {
                // Finally close the stream
                try
                {
                    if (stream != null)
                        stream.Close();
                }
                catch
                {
                }
            }
        }
    }
}
