package me.thekey.android.lib.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.webkit.WebView;
import android.widget.FrameLayout;

import java.lang.ref.WeakReference;

import me.thekey.android.TheKey;
import me.thekey.android.core.CodeGrantAsyncTask;
import me.thekey.android.lib.R;
import me.thekey.android.view.LoginWebViewClient;
import me.thekey.android.view.util.DisplayUtil;

import static me.thekey.android.lib.activity.ActivityBuilder.EXTRA_ARGS;

public class LoginActivity extends Activity {
    public static final String EXTRA_GUID = LoginActivity.class.getName() + ".EXTRA_GUID";

    @NonNull
    /*final*/ Bundle mArgs;

    // login WebView
    private FrameLayout frame = null;
    private WebView loginView = null;

    public static ActivityBuilder builder(final Context context) {
        return new ActivityBuilder(context, LoginActivity.class);
    }

    /* BEGIN lifecycle */

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.thekey_login);

        // get the arguments necessary for creation of TheKey object
        mArgs = getIntent().getBundleExtra(EXTRA_ARGS);
        if (mArgs == null) {
            finish();
            return;
        }

        // init the Login WebView
        this.attachLoginView();
    }

    @Override
    public void onConfigurationChanged(final Configuration newConfig) {
        this.detachLoginView();

        super.onConfigurationChanged(newConfig);

        // reload the view
        setContentView(R.layout.thekey_login);

        // attach the loginView
        this.attachLoginView();
    }

    /* END lifecycle */

    private void attachLoginView() {
        this.detachLoginView();

        // create a loginView if it doesn't exist already
        if (this.loginView == null) {
            this.loginView = DisplayUtil.createLoginWebView(this, new ActivityLoginWebViewClient(), mArgs);
        }

        // attach the login view to the current frame
        frame = findViewById(R.id.loginViewFrame);
        this.frame.addView(this.loginView);
    }

    private void detachLoginView() {
        // remove the login view from any existing frame
        if (this.frame != null) {
            this.frame.removeView(this.loginView);
            this.frame = null;
        }
    }

    private class ActivityLoginWebViewClient extends LoginWebViewClient {
        ActivityLoginWebViewClient() {
            super(LoginActivity.this, mArgs);
        }

        @Override
        protected void onAuthorizeSuccess(@NonNull final Uri uri, @NonNull final String code,
                                          @Nullable final String state) {
            new ActivityCodeGrantAsyncTask(LoginActivity.this, mTheKey, code, state).execute();
        }

        @Override
        protected void onAuthorizeError(final Uri uri, final String errorCode) {
            LoginActivity.this.setResult(RESULT_CANCELED);
            LoginActivity.this.finish();
        }
    }

    private static class ActivityCodeGrantAsyncTask extends CodeGrantAsyncTask {
        private final WeakReference<LoginActivity> mActivity;

        ActivityCodeGrantAsyncTask(@NonNull final LoginActivity activity, @NonNull final TheKey theKey,
                                   @NonNull final String code, @Nullable final String state) {
            super(theKey, null, code, state);
            mActivity = new WeakReference<>(activity);
        }

        @Override
        protected void onPostExecute(final String guid) {
            super.onPostExecute(guid);

            final LoginActivity activity = mActivity.get();
            if (activity != null) {
                if (guid != null) {
                    final Intent response = new Intent();
                    response.putExtra(EXTRA_GUID, guid);
                    activity.setResult(RESULT_OK, response);
                } else {
                    activity.setResult(RESULT_CANCELED);
                }

                activity.finish();
            }
        }
    }
}

@@ -524,16 +524,55 @@
 .lib.R;%0A
+import me.thekey.android.view.Builder;%0A
 import m
@@ -609,24 +609,24 @@
 ViewClient;%0A
-
 import me.th
@@ -660,16 +660,42 @@
 layUtil;
+%0Aimport timber.log.Timber;
 %0A%0Aimport
@@ -1058,24 +1058,32 @@
  static 
+Builder%3C
 Activity
 Builder 
@@ -1074,23 +1074,17 @@
 Activity
-Builder
+%3E
  builder
@@ -1503,16 +1503,16 @@
 _ARGS);%0A
-
         
@@ -1524,32 +1524,201 @@
 Args == null) %7B%0A
+            Timber.tag(%22LoginActivity%22)%0A                    .e(%22Error creating LoginActivity, make sure to use LoginActivity.builder(Context) to create the activity.%22);%0A
             fini

add an error message if LoginActivity was improperly created