using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceData.Complex;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Collections.ObjectModel;
using System.IO;

namespace SerializerPrototype
{
    class Program
    {
         static void Main(string[] args)
        {
            try
            {
                //Serialize("KnownTypeAttributeExample.txt");
                Deserialize("KnownTypeAttributeExample.txt");
                // Run this twice. The second time, comment out the
                // Serialize call and comment out the 
                // KnownTypeAttribute on the Person class. The
                // deserialization will then fail.
            }
            catch (SerializationException exc)
            {
                Console.WriteLine("{0}: {1}", exc.Message,
                    exc.StackTrace);
            }
            finally
            {
                Console.WriteLine("Press Enter to exit...");
                Console.ReadLine();
            }
        }

        public static void Serialize(string path)
        {
            VariousEntities variousEntities = new VariousEntities();
            BusinessEntity business = new BusinessEntity();
            business.Id = 1;
            business.Address = "1212";
            business.City = "city";
            business.State = "st";
            business.Zip = "zip";
            variousEntities.Entities.Add(business);

            DataContractJsonSerializer jsonSer =
                new DataContractJsonSerializer(typeof(VariousEntities), new Collection<Type>() {typeof(BusinessEntity),typeof(CustomerEntity), typeof(VendorEntity)});
            FileStream fs = new FileStream(path, FileMode.Create);
            using (fs)
            {
                jsonSer.WriteObject(fs, variousEntities);
            }

        }

        public static void Deserialize(string path)
        {
            DataContractJsonSerializer jsonSer =
                new DataContractJsonSerializer(typeof(VariousEntities), new Collection<Type>() { typeof(BusinessEntity), typeof(CustomerEntity), typeof(VendorEntity) });
            FileStream fs = new FileStream(path, FileMode.Open);
            using (fs)
            {
                VariousEntities variousEntities = (VariousEntities)jsonSer.ReadObject(fs);
                Console.WriteLine("Count {0}", variousEntities.Entities.Count);
                foreach (object entity in variousEntities.Entities)
                {
                    if (entity as BusinessEntity != null)
                    {
                        Console.WriteLine("Conversion Worked");
                    }
                }
            }
        }
    }
}
