using System;
using System.ComponentModel;
using System.Diagnostics;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Axiom.Utils;

namespace PortfolioManager.ViewModels
{

    public abstract class ModelBase : INotifyPropertyChanged
    {
      public event PropertyChangedEventHandler PropertyChanged;


      public Window GetTopLevelWindow()
      {
        Window currentWindow = default;
        if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
          currentWindow = desktop.MainWindow;
        }
        return currentWindow;
      }

      public virtual String DisplayName
      {
        get;
        protected set;
      }

      protected virtual bool ThrowOnInvalidPropertyName
      {
          get;
          private set;
      }

      protected virtual void OnPropertyChanged(string propertyName)
      {
          this.VerifyPropertyName(propertyName);
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              var e = new PropertyChangedEventArgs(propertyName);
              handler(this, e);
          }
      }

      public void VerifyPropertyName(string propertyName)
      {
          if (TypeDescriptor.GetProperties(this)[propertyName] == null)
          {
              string message = "Invalid property name: " + propertyName;
              MDTrace.WriteLine(LogLevel.DEBUG, message);
              if (this.ThrowOnInvalidPropertyName) throw new Exception(message); else Debug.Fail(message);
          }
      }
  }
}