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

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>,List<Composant>) chargeDonnee()
        { //replacer liste par datatopersiste
            var serializer = new DataContractSerializer(typeof(DataToPersist));
            
            DataToPersist data = new DataToPersist();

            using (Stream stream = File.OpenRead(Path.Combine(FilePath, FileName)))
            {
                data = serializer.ReadObject(stream) as DataToPersist;
            }
            return (data.lu,data.lc); // return entre parentèses data.type1, data.type2
        }
    
        public void sauvegardeDonnee(List<Utilisateur> lu, List<Composant> lc)
        {
            var serializer = new DataContractSerializer (typeof(DataToPersist));
            //Debug.WriteLine(Directory.GetCurrentDirectory());
            Debug.WriteLine("Directory de sauvegarde");
            Debug.WriteLine(Directory.GetCurrentDirectory());
            if (!Directory.Exists(FilePath))
            {
                
                Directory.CreateDirectory(FilePath);
                File.Create(Path.Combine(FilePath, FileName));
            }
            DataToPersist data = new DataToPersist();
            data.lu = lu;
            data.lc = lc;
            var settings = new XmlWriterSettings() { Indent = true };
            using (TextWriter tw = File.CreateText(Path.Combine(FilePath, FileName)))
            {
                using (XmlWriter writer = XmlWriter.Create(tw, settings))
                {
                    serializer.WriteObject(writer, data);
                }
            }
        }
    }
}
