using System;
using Android.App;
using Xamarin.Forms.Platform.Android;
using Xamarin.Auth;
using Xamarin.Forms;
using AuthenticateProviders.Droid;
using AuthenticateProviders;

[assembly: ExportRenderer(typeof(LoginPage), typeof(LoginPageRenderer))]
namespace AuthenticateProviders.Droid {
   class LoginPageRenderer : PageRenderer {
      LoginPage page;
      bool loginInProgress;

      protected override void OnElementChanged(ElementChangedEventArgs<Page> e) {
        base.OnElementChanged(e);
        if (e.OldElement != null || Element == null)
          return;
        page = e.NewElement as LoginPage;
        if (page == null || loginInProgress)
          return;
        loginInProgress = true;
        try {
          // Twój identyfikator kliencki OAuth2
          OAuth2Authenticator auth = new OAuth2Authenticator(
            page.ProviderOAuthSettings.ClientId,
            // Twoje hasło klienckie OAuth2
            page.ProviderOAuthSettings.ClientSecret,
            // Zakresy rozdzielone znakiem "+"
            page.ProviderOAuthSettings.ScopesString,

            new Uri(page.ProviderOAuthSettings.AuthorizeUrl),
            // Przekierowujący adres URL
            new Uri(page.ProviderOAuthSettings.RedirectUrl),
            new Uri(page.ProviderOAuthSettings.AccessTokenUrl)
          );
          auth.AllowCancel = true;
          auth.Completed += async(sender, args) => {
            // Wykonywane operacje
            await page.Navigation.PopAsync();
            loginInProgress = false;
          };
          auth.Error += (sender, args) => {
            Console.WriteLine("Błąd uwierzytelnienia: {0}", args.Exception);
          };
          var activity = Xamarin.Forms.Forms.Context as Activity;
          activity.StartActivity(auth.GetUI(Xamarin.Forms.Forms.Context));
        } catch (Exception ex) {
          Console.WriteLine(ex);
        }
      }
   }
}