using System;
using System.Diagnostics;
using System.Linq;
using Myra.Graphics2D.UI;
using Sledgemapper.Messages;
using Sledgemapper.Shared.Entities;
using TinyMessenger;

namespace Sledgemapper.UI
{
    public partial class LoginRegisterWindow
	{
        private AuthenticateResponse _authResponse;
        private readonly CommunicationManager CommunicationManager;
        private readonly Window Window;
        private readonly TinyMessengerHub _messenger;

		public LoginRegisterWindow(CommunicationManager communicationManager, Window window, TinyMessengerHub messenger)
		{
			BuildUI();
            CommunicationManager=communicationManager;
            Window=window;
            _messenger=messenger;

#if DEBUG
            TxtEmail.Text = "michele.scandura@outlook.com";
            TxtPassword.Text = "slePharland!79";
#endif

            RdoLogin.IsPressed = true;
            RdoLogin.Click += (s, e) =>
            {
                TxtFirstname.Visible = false;
                TxtLastname.Visible = false;
                TxtInitials.Visible = false;
                LblFirstname.Visible = false;
                LblLastname.Visible = false;
                LblInitials.Visible = false;
                BtnLogin.Visible = true;
                BtnRegister.Visible = false;
                Window.Title = "Login";
            };

            RdoRegister.Click += (s, e) =>
            {
                TxtFirstname.Visible = true;
                TxtLastname.Visible = true;
                TxtInitials.Visible = true;
                LblFirstname.Visible = true;
                LblLastname.Visible = true;
                LblInitials.Visible = true;
                BtnLogin.Visible = false;
                BtnRegister.Visible = true;
                Window.Title = "Register";
            };

            BtnRegister.Click += OnButtonRegisterClick;
            BtnLogin.Click += OnButtonLoginClick;
            //TxtEmail.SetKeyboardFocus();

		}



         private async void OnButtonRegisterClick(object sender, EventArgs e)
        {
            var button = ((TextButton)sender);

            var localContent = this;// GetParentContentInWindow<LoginRegisterWindow>(button);// localWindow.Content as PlayerWindow;

            if (!button.Enabled)
            {
                return;
            }

            var isValid = true;
            isValid &= TxtEmail.ValidateTextbox();
            isValid &= TxtPassword.ValidateTextbox();
            isValid &= TxtFirstname.ValidateTextbox();
            isValid &= TxtLastname.ValidateTextbox();
            isValid &= TxtInitials.ValidateTextbox();

            if (!isValid)
            {
                LblLoginError.Text = "Please complete all the fields";
                LblLoginError.Visible = true;
                return;
            }

            var successful = false;
            try
            {
                button.Text = "Wait...";
                LblLoginError.Text = "";
                LblLoginError.Visible = false;

                var result = await CommunicationManager.Register(new RegisterModel
                {
                    Username = TxtEmail.Text,
                    Email = TxtEmail.Text,
                    Password = TxtPassword.Text,
                    FirstName = TxtFirstname.Text,
                    LastName = TxtLastname.Text,
                    Initials = TxtInitials.Text
                });
                if (result.Result)
                {
                    _authResponse = await CommunicationManager.Login(new AuthenticateModel
                    {
                        Username = TxtEmail.Text,
                        Password = TxtPassword.Text
                    });
                    successful = true;
                }
                else
                {
                    LblLoginError.Text = result.Errors.FirstOrDefault();
                    LblLoginError.Visible = true;
                }
            }
            catch (Refit.ApiException refitException)
            {
                //ExceptionlessClient.Default.SubmitException(refitException);
                LblLoginError.Text = refitException.Content;
                LblLoginError.Visible = true;
            }
            catch (Exception ex)
            {
                //ExceptionlessClient.Default.SubmitException(ex);
                LblLoginError.Text = "Can't connect to the server";
                LblLoginError.Visible = true;
                Debug.Write(ex);
            }
            finally
            {
                button.Enabled = true;
                button.Text = "Register";
            }
            if (successful)
            {
                _messenger.Publish(new LoginSuccesfulMessage(this){UserName=_authResponse.Username, Initials=_authResponse.Initials});
                localContent.Window.Close();
            }
        }

        private async void OnButtonLoginClick(object sender, EventArgs e)
        {
            var button = ((TextButton)sender);
            Container container = button.Parent;
            while (!(container is Window))
            {
                container = container.Parent;
            }

            var localWindow = (Window)container;
            var localContent = localWindow.Content as LoginRegisterWindow;

            if (!button.Enabled)
            {
                return;
            }

            var isValid = true;
            isValid &= localContent.TxtEmail.ValidateTextbox();
            isValid &= localContent.TxtPassword.ValidateTextbox();

            if (!isValid)
            {
                localContent.LblLoginError.Text = "Username or password is not valid";
                localContent.LblLoginError.Visible = true;

                return;
            }

            var successful = false;
            try
            {
                button.Text = "Wait...";
                localContent.LblLoginError.Text = "";
                localContent.LblLoginError.Visible = false;
                _authResponse = await CommunicationManager.Login(new AuthenticateModel
                {
                    Username = localContent.TxtEmail.Text,
                    Email = localContent.TxtEmail.Text,
                    Password = localContent.TxtPassword.Text
                });
                successful = _authResponse != null;
            }
            catch (Refit.ApiException refitException)
            {
                //ExceptionlessClient.Default.SubmitException(refitException);
                localContent.LblLoginError.Text = refitException.Content;
                localContent.LblLoginError.Visible = true;
            }
            catch (Exception ex)
            {
                //ExceptionlessClient.Default.SubmitException(ex);
                localContent.LblLoginError.Text = "Can't connect to the server";
                localContent.LblLoginError.Visible = true;
                Debug.Write(ex);
            }
            finally
            {
                button.Enabled = true;
                button.Text = "Login";
            }

            if (successful)
            {
                _messenger.Publish(new LoginSuccesfulMessage(this){UserName=_authResponse.Username, Initials=_authResponse.Initials});
                localWindow.Close();
            }
        }
	}


    
}