using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace BO.Utils
{
  public static class XmlUtil
  {
    public static void SerializerObjToFile(object obj, string fileName = "")
    {
      if (string.IsNullOrWhiteSpace(fileName))
      {
        fileName = obj.GetType().Name + ".xml";
      }

      var ser = new XmlSerializer(obj.GetType());
      using (var stream = File.Open(fileName, FileMode.Create))
      {
        ser.Serialize(stream, obj);
      }
    }

    public static T DeserializeFromFile<T>(string fileName = "")
      where T : new()
    {
      if (string.IsNullOrWhiteSpace(fileName))
      {
        fileName = typeof(T).Name + ".xml";
      }
      if (!File.Exists(fileName))
      {
        return new T();
      }
      using (var reader = new StreamReader(fileName))
      {
        var xs = new XmlSerializer(typeof(T));
        object obj = xs.Deserialize(reader);
        reader.Close();
        return (T)obj;
      }
    }

    public static T XmlDeserializeObject<T>(string xmlOfObject) where T : class
    {
      using (MemoryStream ms = new MemoryStream())
      {
        using (StreamWriter sr = new StreamWriter(ms, Encoding.UTF8))
        {
          sr.Write(xmlOfObject);
          sr.Flush();
          ms.Seek(0, SeekOrigin.Begin);
          XmlSerializer serializer = new XmlSerializer(typeof(T));
          return serializer.Deserialize(ms) as T;
        }
      }
    }
  }

  public class ClientVersion
  {
    public string Version { get; set; }

    public string ServerUrl { get; set; }
  }
}
