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; }
        public string FileName { get; set; } = "UserData.xml";
        

        public DataContractPers() 
        { }

        public DataToPersist chargeDonnee()
        {
            //-- Chemin de sauvegarde --//
            string appDirectory = AppContext.BaseDirectory;
            int sousDossier = 53;
            FilePath = appDirectory.Substring(0, appDirectory.Length - sousDossier);
            Directory.SetCurrentDirectory(FilePath);
            FilePath = Path.Combine(FilePath, "Data");


            var serializer = new DataContractSerializer(typeof(DataToPersist));
            DataToPersist data = new DataToPersist();
            //-- Read fichier--//
            using (Stream stream = File.OpenRead(Path.Combine(FilePath, FileName)))
            {
                data = serializer.ReadObject(stream) as DataToPersist;
            }
            return data;
        }
    
        public void sauvegardeDonnee(DataToPersist data)
        {
            //-- Chemin de sauvegarde --//
            string appDirectory = AppContext.BaseDirectory;
            int sousDossier = 53;
            FilePath = appDirectory.Substring(0, appDirectory.Length - sousDossier);
            Directory.SetCurrentDirectory(FilePath);
            FilePath = Path.Combine(FilePath, "Data");

            //-- Vérifie si le fichier et dossier existe déjà --//
            var serializer = new DataContractSerializer (typeof(DataToPersist));
            if (!Directory.Exists(FilePath))
            {
                
                Directory.CreateDirectory(FilePath);
            }

            //-- Write fichier --//
            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);
                }
            }
        }
    }
}
