using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;

using Cirrious.FluentLayouts;
using Cirrious.FluentLayouts.Touch;

using TeenTix.Common;
using TeenTix.Common.Model;

namespace TeenTixMobileNEW
{
	partial class LoginController : UIViewController
	{
		public LoginController(IntPtr handle) : base(handle)
		{
		}

		public override void ViewDidLoad()
		{
			base.ViewDidLoad();

			View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();

			View.AddConstraints(
				InstructionsLabel.AtTopOf(View, 60),
				InstructionsLabel.AtLeftOf(View, 20),

				EmailLabel.Below(InstructionsLabel, 5),
				EmailLabel.AtLeftOf(View, 20),

				LoginEmail.WithSameCenterY(EmailLabel),

				PasswordLabel.Below(EmailLabel, 10),
				PasswordLabel.WithSameLeft(EmailLabel),
				PasswordLabel.Width().EqualTo(92),

				EmailLabel.WithSameRight(PasswordLabel),

				LoginPassword.Height().EqualTo(30),


				LoginPassword.ToRightOf(PasswordLabel, 10),
				LoginPassword.AtRightOf(View).Minus(20),
				LoginPassword.WithSameCenterY(PasswordLabel),

				LoginEmail.WithSameLeft(LoginPassword),
				LoginEmail.WithSameRight(LoginPassword),
				LoginEmail.WithSameHeight(LoginPassword),

				LoginMessage.WithSameCenterX(View),
				LoginMessage.Below(LoginPassword, 5),
				LoginMessage.WithSameWidth(View),

				LoginButton.Height().EqualTo(60),
				LoginButton.Below(LoginMessage, 5),
				LoginButton.WithSameWidth(View),

				ForgotPasswordButton.Height().EqualTo(60),
				ForgotPasswordButton.Below(LoginButton, 5),
				ForgotPasswordButton.WithSameWidth(View)
			);

			this.LoginEmail.ShouldReturn += (textField) =>
			{
				textField.ResignFirstResponder();
				return true;
			};


			this.LoginPassword.ShouldReturn += (textField) =>
			{
				textField.ResignFirstResponder();
				return true;
			};

			LoginButton.TouchUpInside += async (object sender, EventArgs e) =>
			{
				var loginRequest = LoginFromForm();
				var valid = AccountManager.ValidateLogin(loginRequest);
				if (!valid.Valid)
				{
					LoginMessage.Text = valid.Message;
					return;
				}

				DisableFormAndShowSpinner();

				LoginResult result;
				using (new NetworkActivityUtil())
					result = await AccountManager.Login(LoginFromForm());

				if (result.Success)
				{
					RestAPI.Session = result.Session;
					KeychainUtil.StoreCredential(Credential.Create(loginRequest.Email, loginRequest.Password));
					PerformSegue("SegueToCurate", this);
					ResetForm();
				}
				else {
					EnableFormAndShowError(result.ErrorMessage);
				}
			};

			ForgotPasswordButton.TouchUpInside += (object sender, EventArgs e) =>
			{
				var confirmController = UIAlertController.Create(
					"Forgot Password",
					"Open forgot password page in browser?",
					UIAlertControllerStyle.Alert
				);
				confirmController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, (UIAlertAction obj) =>
				{
					UIApplication.SharedApplication.OpenUrl(new NSUrl(PrivateConstants.HOST_URL + "/account/password"));
				}));
				confirmController.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));
				PresentViewController(confirmController, true, null);
			};
		}

		private void DisableFormAndShowSpinner()
		{
			// TODO: implement me!
		}

		private void EnableFormAndShowError(string errorMessage)
		{
			// TODO: implement form enable! (thomasvandoren, 2016-02-27)
			LoginMessage.Text = errorMessage;
		}

		private void ResetForm()
		{
			LoginEmail.Text = "";
			LoginPassword.Text = "";
		}

		private LoginRequest LoginFromForm()
		{
			var result = new LoginRequest();
			result.Email = LoginEmail.Text;
			result.Password = LoginPassword.Text;
			return result;
		}
	}
}
