using Microsoft.UI.Xaml.Controls;
using Sonex.Client.Helpers;
using Sonex.Client.Models;
using System;
using System.Diagnostics;

namespace Sonex.Client.Dialogs
{
    public sealed partial class CreateNewAccountDialog : ContentDialog
    {
        public long AccountId { get; private set; } = -1;

        public CreateNewAccountDialog()
        {
            InitializeComponent();
        }

        private async void CreateNewAccountDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            var deferral = args.GetDeferral();
            args.Cancel = true;

            try
            {
                _Message.Text = string.Empty;
                IsPrimaryButtonEnabled = false;
                IsSecondaryButtonEnabled = false;

                var result = await AccountModel.New(
                    _FirstName.Text,
                    _LastName.Text,
                    _AccountName.Text,
                    _Password.Password);

                if (result != null && result.Success)
                {
                    AccountId = result.Item;
                    args.Cancel = false;
                    Debug.WriteLine("Create Account id: " + AccountId);
                }
                else
                {
                    _Message.Text = result?.ErrorMessage;
                    // dialog zostaje otwarty
                    // tutaj najlepiej pokaż błąd wewnątrz dialogu, np. TextBlock / InfoBar
                    Debug.WriteLine(result?.ErrorMessage ?? "CreateNewAccount failed.");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                // dialog zostaje otwarty
            }
            finally
            {
                IsPrimaryButtonEnabled = true;
                IsSecondaryButtonEnabled = true;
                deferral.Complete();
            }
        }
    }
}