/*
 * WebViewActivity.java
 *
 * Copyright(c) 2016 Auth0 (http://auth0.com)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.auth0.android.lock.provider;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ProgressBar;

import com.auth0.android.lock.R;

public class WebViewActivity extends AppCompatActivity {

    public static final String CONNECTION_NAME_EXTRA = "serviceName";
    public static final String KEY_REDIRECT_URI = "redirect_uri";

    private WebView webView;
    private ProgressBar progressBar;
    private Button retryButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.com_auth0_lock_activity_web_view);
        final ActionBar bar = getSupportActionBar();
        if (bar != null) {
            String serviceName = getIntent().getStringExtra(CONNECTION_NAME_EXTRA);
            bar.setIcon(android.R.color.transparent);
            bar.setDisplayShowTitleEnabled(false);
            bar.setDisplayUseLogoEnabled(false);
            bar.setDisplayHomeAsUpEnabled(false);
            bar.setDisplayShowCustomEnabled(true);
            bar.setTitle(serviceName);
        }
        webView = (WebView) findViewById(R.id.com_auth0_lock_webview);
        webView.setVisibility(View.INVISIBLE);
        progressBar = (ProgressBar) findViewById(R.id.com_auth0_lock_progressbar);
        progressBar.setIndeterminate(true);
        progressBar.setMax(100);
        retryButton = (Button) findViewById(R.id.com_auth0_lock_retry);
        retryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                retryButton.setVisibility(View.GONE);
                startUrlLoading();
            }
        });

        startUrlLoading();
    }

    private void startUrlLoading() {
        if (!isNetworkAvailable()) {
            renderNetworkError();
            return;
        }

        final Intent intent = getIntent();
        final Uri uri = intent.getData();
        final String redirectUrl = uri.getQueryParameter(KEY_REDIRECT_URI);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress > 0) {
                    progressBar.setIndeterminate(false);
                    progressBar.setProgress(newProgress);
                }
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith(redirectUrl)) {
                    final Intent intent = new Intent();
                    intent.setData(Uri.parse(url));
                    setResult(RESULT_OK, intent);
                    finish();
                    return true;
                }
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progressBar.setProgress(100);
                progressBar.setIndeterminate(true);
                progressBar.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setProgress(0);
                progressBar.setIndeterminate(false);
                progressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                renderNetworkError();
            }

        });
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.loadUrl(uri.toString());
    }

    private void renderNetworkError() {
        webView.setVisibility(View.INVISIBLE);
        retryButton.setVisibility(View.VISIBLE);
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
    }
}
@@ -1498,16 +1498,41 @@
 tivity;%0A
+import android.util.Log;%0A
 import a
@@ -1897,29 +1897,30 @@
 ity %7B%0A%0A    p
-ublic
+rivate
  static fina
@@ -1932,57 +1932,64 @@
 ing 
-CONNECTION_NAME_EXTRA = %22servic
+TAG = WebViewActivity.class.getSimpl
 eName
-%22
+()
 ;%0A    p
-ublic
+rivate
  sta
@@ -2039,16 +2039,86 @@
 ct_uri%22;
+%0A    public static final String CONNECTION_NAME_EXTRA = %22serviceName%22;
 %0A%0A    pr
@@ -6042,24 +6042,58 @@
 ailable() %7B%0A
+        boolean available = true;%0A
         Conn
@@ -6196,24 +6196,42 @@
 Y_SERVICE);%0A
+        try %7B%0A    
         Netw
@@ -6310,22 +6310,31 @@
         
-return
+    available =
  activeN
@@ -6396,19 +6396,256 @@
 nnecting();%0A
+        %7D catch (SecurityException e) %7B%0A            Log.w(TAG, %22Could not check for Network status. Please, be sure to include the android.permission.ACCESS_NETWORK_STATE permission in the manifest%22);%0A        %7D%0A        return available;%0A
     %7D%0A%7D

handle missing permission when checking network status