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

namespace ButcherFactory.BO.Utils
{
  public static class XmlUtil
  {
    static string config = "Config";
    public static void SerializerObjToFile(object obj, string fileName = "")
    {
      if (string.IsNullOrWhiteSpace(fileName))
      {
        fileName = Path.Combine(config, 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 = Path.Combine(config, typeof(T).Name + ".xml");
      }
      if (!File.Exists(fileName))
      {
        return new T();
      }
      using (var reader = new StreamReader(fileName))
      {
        var xs = new XmlSerializer(typeof(T));
        try
        {
          object obj = xs.Deserialize(reader);
          return (T)obj;
        }
        catch
        {
          return new T();
        }
        finally
        {
          reader.Close();
        }
      }
    }

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

    public static string ReadAllText(string fileName)
    {
      var path = Path.Combine(config, fileName);
      if (File.Exists(path))
      {
        return File.ReadAllText(path);
      }
      return null;
    }
  }
}
