/* Generated by MyraPad at 02/09/2021 16:26:04 */
using Microsoft.AspNetCore.SignalR.Client;
using Myra.Graphics2D.UI;
using Sentry;
using Sledgemapper.Messages;
using System;
using TinyMessenger;

namespace Sledgemapper.UI
{
    public partial class MapWindow
    {
        public CommunicationManager CommunicationManager { get; }
        public TinyMessengerHub Messenger { get; }

        public MapWindow(CommunicationManager communicationManager, TinyMessengerHub messenger)
        {
            CommunicationManager= communicationManager;
            Messenger = messenger;
            BuildUI();
            BtnNewCampaign.Click += OnButtonNewMapClicked;
        }

        private async void OnButtonNewMapClicked(object sender, EventArgs e)
        {
            Container container = ((TextButton)sender).Parent;
            while (!(container is Window))
            {
                container = container.Parent;
            }
 
            var localContent = ((TextButton)sender).GetParentContentInWindow<MapWindow>();// localWindow.Content as PlayerWindow;

            var isValid = localContent.Content.TxtCampaign.ValidateTextbox();
            if (!isValid)
            {
                return;
            }

            if (CommunicationManager.Connection.State != HubConnectionState.Connected)
            {
                Messenger.Publish(new SignalrConnectionUpdateMessage(this));
            }

            var successful = false;
            Guid sessionGuid = Guid.Empty;
            try
            {
                sessionGuid = await CommunicationManager.Api.NewSession(State.Instance.CampaignId, localContent.Content.TxtCampaign.Text);

                successful = sessionGuid != Guid.Empty;

            }
            catch (Exception ex)
            {
                SentrySdk.CaptureException(ex);
            }

            if (successful)
            {
                Messenger.Publish(new MapOpenedMessage(this, localContent.Content.TxtCampaign.Text, sessionGuid));
                localContent.Window.Close();
            }
        }
    }
}