using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml;

namespace CoreLibrary.Persistance
{
    public class PersistanceJSON : IPersistance
    {

        public T[] Charger<T>() where T : IEstPersistant
        {
            string fichier = $"{typeof(T).Name.ToLower()}s.json";

            Directory.SetCurrentDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../../../../.."));

            if (!Directory.Exists("Fichiers"))
                return [];

            Directory.SetCurrentDirectory(Path.Combine(Directory.GetCurrentDirectory(), "Fichiers"));

            if (!File.Exists(fichier))
                return [];

            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T[]));
            T[] elements;

            using (FileStream s = File.OpenRead(fichier))
            {
                elements = jsonSerializer.ReadObject(s) as T[];
            }

            return elements;
        }

        public void Enregistrer<T>(T[] elements) where T : IEstPersistant
        {
            string fichier = $"{typeof(T).Name.ToLower()}s.json";

            Directory.SetCurrentDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../../../../.."));

            if (!Directory.Exists("Fichiers"))
                Directory.CreateDirectory("Fichiers");

            Directory.SetCurrentDirectory(Path.Combine(Directory.GetCurrentDirectory(), "Fichiers"));

            DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T[]));

            using(FileStream s = File.Create(fichier))
            {
                using(XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(
                                        s,
                                        Encoding.UTF8,
                                        false,
                                        true))
                {
                    jsonSerializer.WriteObject(writer, elements);
                }
            }
        }
    }
}