/* Generated by MyraPad at 10/11/2020 10:59:36 */
using System;
using Microsoft.AspNetCore.SignalR.Client;
using Myra.Graphics2D.UI;
using Sentry;
using Sledgemapper.Messages;
using Sledgemapper.Shared.Entities;
using TinyMessenger;
using Session = Sledgemapper.Shared.Entities.Session;

namespace Sledgemapper.UI
{
    public partial class SessionWindow
    {

        private readonly CommunicationManager CommunicationManager;
        private readonly Window Window;
        private readonly TinyMessengerHub Messenger;


        public SessionWindow(CommunicationManager communicationManager, TinyMessengerHub messenger, Window window)
        {
            BuildUI();
            CommunicationManager = communicationManager;
            Messenger = messenger;
            Window = window;
            BtnLogin.Text = "Join";
            BtnLogin.Click += OnButtonNewSessionClicked;
        }

        private async void OnButtonNewSessionClicked(object sender, EventArgs e)
        {
            var localContent = ((TextButton)sender).GetParentContentInWindow<SessionWindow>();// localWindow.Content as PlayerWindow;

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

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

            var successful = false;
            try
            {
                var result = await CommunicationManager.Api.NewSession(State.Instance.CampaignName, localContent.Content.TxtSession.Text);

                if (result)
                {
                    CommunicationManager.SessionData.SessionName = localContent.Content.TxtSession.Text;

                }
                successful = result;
                var result2 = await CommunicationManager.Connection?.InvokeAsync<Session>("JoinSession", localContent.Content.TxtSession.Text);
                CommunicationManager.SessionData.SessionId = result2.SessionId;
                CommunicationManager.SessionData.SessionName = localContent.Content.TxtSession.Text;
            }
            catch (Exception ex)
            {
                SentrySdk.CaptureException(ex);
            }

            if (successful)
            {
                CommunicationManager.SessionData.SessionName = localContent.Content.TxtSession.Text;
                CommunicationManager.SessionData.Map = CommunicationManager.SessionData.Map;
                CommunicationManager.SessionData.Overlays = CommunicationManager.SessionData.Overlays;
                CommunicationManager.SessionData.Walls = CommunicationManager.SessionData.Walls;

                localContent.Window.Close();
            }
        }
    }
}