using Microscopic_Traffic_Simulator___Model.GeometricObjects.Lanes;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Microscopic_Traffic_Simulator___Model.GeometricObjects
{
    /// <summary>
    /// Class representing geometric topology of road network.
    /// </summary>
    [Serializable]
    public class GeometricTopology
    {
        /// <summary>
        /// Lanes in geometric topology.
        /// </summary>
        private List<Lane> lanes = new List<Lane>();
        /// <summary>
        /// Lanes in geometric topology.
        /// </summary        
        public ReadOnlyCollection<Lane> Lanes { get { return lanes.AsReadOnly(); } }

        /// <summary>
        /// Flag indicating if geometric topology is empty.
        /// </summary>
        public bool IsEmpty { get { return lanes.Count == 0; } }

        /// <summary>
        /// Adds new lane to geometric topology.
        /// </summary>
        /// <param name="newLane">New lane to add.</param>
        public void AddLane(Lane newLane)
        {
            lanes.Add(newLane);
        }

        /// <summary>
        /// Save geometric topology to file.
        /// </summary>
        /// <param name="path">Path to file.</param>
        public void Serialize(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                new BinaryFormatter().Serialize(fs, this);
            }
        }

        /// <summary>
        /// Load geometric topology from file.
        /// </summary>
        /// <param name="path">Path to file.</param>
        /// <returns>Loaded geometric topology.</returns>
        public static GeometricTopology Deserialize(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                GeometricTopology loadedTopology = (GeometricTopology)new BinaryFormatter().Deserialize(fs);
                if (loadedTopology.lanes == null)
                {
                    loadedTopology.lanes = new List<Lane>();
                }
                return loadedTopology;
            }
        }
    }
}
