using System;
using System.Windows;
using MarcusLaw.OutlookAddin.UI.ViewModels;

namespace MarcusLaw.OutlookAddin.UI.Dialogs
{
    public partial class SettingsDialog : Window
    {
        private SettingsViewModel? _viewModel;

        public SettingsDialog()
        {
            InitializeComponent();
        }

        public SettingsDialog(SettingsViewModel viewModel) : this()
        {
            AttachViewModel(viewModel);
        }

        public void AttachViewModel(SettingsViewModel viewModel)
        {
            if (_viewModel != null)
            {
                _viewModel.RequestClose -= OnRequestClose;
                _viewModel.ApiKeyReader = null;
            }
            _viewModel = viewModel ?? throw new ArgumentNullException(nameof(viewModel));
            DataContext = _viewModel;
            _viewModel.RequestClose += OnRequestClose;
            _viewModel.ApiKeyReader = () => ApiKeyBox.Password;
            if (!string.IsNullOrEmpty(_viewModel.InitialApiKey))
            {
                ApiKeyBox.Password = _viewModel.InitialApiKey;
            }
        }

        private void OnRequestClose(object? sender, EventArgs e)
        {
            DialogResult = _viewModel?.DialogResult;
            Close();
        }
    }
}
