using CanYouBuildIt.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace CanYouBuildIt.DataContractPersistance
{
    public class DataContractPers : IPersistanceManager
    {
        public string FilePath { get; set; } = Path.Combine(Directory.GetCurrentDirectory(),"\\Data");
        public string FileName { get; set; } = "UserData.xml";
        

        public DataContractPers() { }

        public List<Utilisateur> chargeDonnee()
        {
            var serializer = new DataContractSerializer(typeof(Utilisateur));
            
            List<Utilisateur> lu = new List<Utilisateur>();

            using (Stream stream = File.OpenRead(Path.Combine(FilePath, FileName)))
            {
                lu = serializer.ReadObject(stream) as List<Utilisateur>;
            }
            return lu;
        }
    
        public bool sauvegardeDonnee(List<Utilisateur> lu)
        {
            DataContractSerializer serializer = new DataContractSerializer (typeof(Utilisateur));
            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
                File.Create(Path.Combine(FilePath, FileName));
            }
            else
            {
                using (Stream stream = File.OpenWrite(Path.Combine(FilePath, FileName)))
                {
                    serializer.WriteObject(stream, lu);
                }
            }
            return true;
        }
    }
}
