using Microsoft.UI.Xaml.Controls;
using Sonex.Data.Records;
using System;
using System.Diagnostics;
using Logger = Sonex.Client.Helpers.Logger;

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

        public CreateNewGroupDialog()
        {
            InitializeComponent();
        }

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

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

                var result = await GroupRecord.Create(
                    _GroupName.Text,
                    _Description.Text);

                if (result != null && result.Success)
                {
                    GroupId = result.Item;
                    args.Cancel = false;
                    Debug.WriteLine("Create Group id: " + GroupId);
                }
                else
                {
                    _Message.Text = result?.ErrorMessage;
                    Debug.WriteLine(result?.ErrorMessage ?? "CreateNewGroup failed.");
                }
            }
            catch (Exception ex)
            {
                string errorId = Logger.Error(
                    ex,
                    source: nameof(CreateNewGroupDialog),
                    operation: "CreateNewGroupDialog_PrimaryButtonClick");
                _Message.Text = Logger.BuildUserMessage(errorId);
            }
            finally
            {
                IsPrimaryButtonEnabled = true;
                IsSecondaryButtonEnabled = true;
                deferral.Complete();
            }
        }
    }
}
