
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace ReAct_PME.WPF_FrameWork
{
    public class BaseViewModel : INotifyPropertyChanged
    {
        public static readonly ServiceProvider ServiceProvider = new ServiceProvider();

        private IOpenDialogService? _openDialog;
        public IOpenDialogService? OpenDialog
        {
            get { return _openDialog; }
        }

        private IMessageBoxService? _msgBox;
        public IMessageBoxService? MsgBox
        {
            get { return _msgBox; }
        }

        private IShowWindowService? _windowChild;
        public IShowWindowService? WindowChild
        {
            get { return _windowChild; }
        }

        static BaseViewModel()
        {
            //Ajouter les différents services
            RegisterDefaultServices();
        }

        protected BaseViewModel() 
        { 
            FetchDefaultServices(); 
        } 

        private static void RegisterDefaultServices()
        {
            // Ajoute les service au fournisseur de services
            ServiceProvider.Add(typeof(IMessageBoxService), new MessageBoxService());
            ServiceProvider.Add(typeof(IShowWindowService), new ShowWindowService());
            ServiceProvider.Add(typeof(IOpenDialogService), new OpenDialogService());
        }

        private void FetchDefaultServices()
        {
            // Extraire le service du fournisseur
            _msgBox = this.Resolve<IMessageBoxService>();
            _windowChild = this.Resolve<IShowWindowService>();
            _openDialog = this.Resolve<IOpenDialogService>();
        }

        protected T? Resolve<T>()
        {
            return ServiceProvider.Resolve<T>();
        }


        // Event pour notifier des changements
        public event PropertyChangedEventHandler? PropertyChanged;

        // Méthode utilitaire pour déclencher les notifications de changement
        protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
        {
            if (propertyName is null)
                return;

            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        // Optionnel : méthode pour mettre à jour une propriété et déclencher automatiquement les notifications
        protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)
        {
            if (propertyName is null)
                return false;

            if (!EqualityComparer<T>.Default.Equals(field, value))
            {
                field = value;
                OnPropertyChanged(propertyName);
                return true;
            }
            return false;
        }
    }
}

