using System;
using System.Collections.Generic;
using System.Json;
using System.Linq;
using System.Threading.Tasks;
using MonoTouch.Dialog;

#if __UNIFIED__
using Foundation;
using UIKit;
#else
using MonoTouch.Foundation;
using MonoTouch.UIKit;
#endif

namespace Xamarin.Auth.Sample.iOS
{
	[Register ("AppDelegate")]
	public partial class AppDelegate : UIApplicationDelegate
	{
		void LoginToFacebook (bool allowCancel)
		{
			var auth = new OAuth2Authenticator (
				clientId: "Identyfikator aplikacji z https://developers.facebook.com/apps",
				scope: "",
				authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
				redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));

			auth.AllowCancel = allowCancel;

			// Jeżeli uwierzytelnienie powiedzie się lub zostanie przerwane, wywoływana jest
      // metoda .Completed
			auth.Completed += (s, e) =>
			{
				// My wyświetlamy okno, więc od nas zależy, czy je zamkniemy
				dialog.DismissViewController (true, null);

				if (!e.IsAuthenticated) {
					facebookStatus.Caption = "Nie uwierzytelniony";
					dialog.ReloadData();
					return;
				}

				// Po zalogowaniu wysyłamy zapytanie OAuth2 o dane użytkownika
				var request = new OAuth2Request ("GET", new Uri ("https://graph.facebook.com/me"), null, e.Account);
				request.GetResponseAsync().ContinueWith (t => {
					if (t.IsFaulted)
						facebookStatus.Caption = "Błąd: " + t.Exception.InnerException.Message;
					else if (t.IsCanceled)
						facebookStatus.Caption = "Anulowano";
					else
					{
						var obj = JsonValue.Parse (t.Result.GetResponseText());
						facebookStatus.Caption = "Zalogowany jako " + obj["name"];
					}

					dialog.ReloadData();
				}, uiScheduler);
			};

			UIViewController vc = auth.GetUI ();
			dialog.PresentViewController (vc, true, null);
		}

		public override bool FinishedLaunching (UIApplication app, NSDictionary options)
		{
			facebook = new Section ("Facebook");
			facebook.Add (new StyledStringElement ("Zaloguj", () => LoginToFacebook (true)));			
			facebook.Add (new StyledStringElement ("Zaloguj (bez anulowania)", () => LoginToFacebook (false)));
			facebook.Add (facebookStatus = new StringElement (String.Empty));

			dialog = new DialogViewController (new RootElement ("Przykład Xamarin.Auth") {
				facebook,
			});

			window = new UIWindow (UIScreen.MainScreen.Bounds);
			window.RootViewController = new UINavigationController (dialog);
			window.MakeKeyAndVisible ();
			
			return true;
		}

		private readonly TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

		UIWindow window;
		DialogViewController dialog;

		Section facebook;
		StringElement facebookStatus;

		// Główny punkt wejścia aplikacji
		static void Main (string[] args)
		{
			UIApplication.Main (args, null, "AppDelegate");
		}
	}
}

