namespace inutralia.Views
{
    using System;
    using inutralia.Models;
    using Xamarin.Forms;

    public partial class LoginView : ContentPage
    {
        private bool processing
        {
            set { loginButton.IsEnabled = !value; }
        }

        public LoginView()
        {
            InitializeComponent();

            if (Application.Current.Properties.ContainsKey("Username")) userEntry.Text = Application.Current.Properties["Username"].ToString();
            if (Application.Current.Properties.ContainsKey("Password")) passwordEntry.Text = Application.Current.Properties["Password"].ToString();
        }

        async void OnLoginButtonClicked(object sender, EventArgs e)
        {
            processing = true;

            Application.Current.Properties["Username"] = userEntry.Text;
            Application.Current.Properties["Password"] = passwordEntry.Text;

            var Username = userEntry.Text;
            var Password = passwordEntry.Text;

            App.API.CredentialsSet(Username, Password);

            try
            {
                var users = await App.API.RefreshListAsync<User>();

                if (users.Count > 0)
                {
                    App.IsUserLoggedIn = true;

                    Page nextView = new RootPage() as Page;

                    // Cambiar de vista
                    Application.Current.MainPage = nextView;
                }

                else
                {
                    throw new Exception();
                }
            }

            catch (Exception err)
            {
                await DisplayAlert("Error", "El usuario o la contraseña no son correctos", "Entendido");
            }

            processing = false;
        }

        protected override void OnDisappearing()
        {
            base.OnDisappearing();
        }
    }
}
