using Microsoft.Maui.Controls.PlatformConfiguration;
using MusiLib.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace MusiLib.DataContractPersistance
{
    public class DataContractPers : IPersistanceManager
    {
        public string FilePath { get; set; } = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/musilib";
        public string FileNameP { get; set; } = "UserFavoris.xml";
        public string FileNameU { get; set; } = "UserData.xml";

        public (List<Partition>, List<Utilisateur>) chargeDonnees()
        {
            var serializerP = new DataContractSerializer(typeof(List<Partition>));
            var serializerU = new DataContractSerializer(typeof(List<Utilisateur>), new[] { typeof(Partition) });

            List<Partition> partitions = new List<Partition>();
            List<Utilisateur> utilisateurs = new List<Utilisateur>();

            string pathP = Path.Combine(FilePath, FileNameP);
            if (File.Exists(pathP))
            {
                using (Stream stream = File.OpenRead(pathP))
                {
                    partitions = serializerP.ReadObject(stream) as List<Partition>;
                }
            }

            string pathU = Path.Combine(FilePath, FileNameU);
            if (File.Exists(pathU))
            {
                using (Stream stream = File.OpenRead(pathU))
                {
                    utilisateurs = serializerU.ReadObject(stream) as List<Utilisateur>;
                }
            }

            return (partitions, utilisateurs);
        }

        public void sauvegardeDonnees(List<Partition> p, List<Utilisateur> u)
        {
            var serializerP = new DataContractSerializer(typeof(List<Partition>));
            var serializerU = new DataContractSerializer(typeof(List<Utilisateur>), new[] { typeof(Partition) });

            if (!Directory.Exists(FilePath))
            {
                System.Diagnostics.Debug.WriteLine("Directory créé à l'instant");
                System.Diagnostics.Debug.WriteLine(FilePath);
                Directory.CreateDirectory(FilePath);
            }

            using (Stream stream = File.Create(Path.Combine(FilePath, FileNameP)))
            {
                serializerP.WriteObject(stream, p);
            }

            using (Stream stream = File.Create(Path.Combine(FilePath, FileNameU)))
            {
                serializerU.WriteObject(stream, u);
            }
        }
    }
}