/**
 * Copyright (C) 2020 SIL International. All rights reserved.
 */

package com.tavultesoft.kmea;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;

public class KMPBrowserActivity extends AppCompatActivity {

  private WebView webView;
  private static final String KMP_SEARCH_BASE_URL = "https://keyman.com/keyboards";
  private static final String KMP_LANGUAGE = "/languages/";
  private static final String KMP_QUERY = "?embed=linux&version="; // TODO: Update to Android
  private boolean isLoading = false;
  private boolean didFinishLoading = false;

  @SuppressLint({"SetJavaScriptEnabled", "InflateParams"})
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final Context context = this;

    setContentView(R.layout.activity_kmp_browser);

    webView = (WebView) findViewById(R.id.kmpBrowserWebView);
    webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setSupportZoom(true);
    webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

    webView.setWebChromeClient(new WebChromeClient() {
      public void onProgressChanged(WebView view, int progress) {
      }
    });
    webView.setWebViewClient(new WebViewClient() {
      @Override
      public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        didFinishLoading = true;
        isLoading = false;
      }

      @Override
      public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (!url.toLowerCase().equals("about:blank")) {
          if (url.startsWith("keyman:download")) {
            // KMAPro main activity will handle this intent
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivityForResult(intent, 1);
          } else {
            view.loadUrl(url);
          }
        }
        return true;
      }

      @Override
      public void onPageStarted(WebView view, String url, Bitmap favicon) {
        isLoading = true;
        didFinishLoading = false;
      }

      @Override
      public void onPageFinished(WebView view, String url) {
        didFinishLoading = true;
        isLoading = false;
      }
    });

    // If language ID is provided, include it in the keyboard search
    String languageID = getIntent().getStringExtra("languageCode");
    String languageStr = (languageID != null) ? String.format("%s%s", KMP_LANGUAGE, languageID) : "";
    String appVersion = KMManager.getVersion();
    String kmpSearchUrl = String.format("%s%s%s%s", KMP_SEARCH_BASE_URL, languageStr, KMP_QUERY, appVersion);
    webView.loadUrl(kmpSearchUrl);
  }

  @Override
  protected void onResume() {
    super.onResume();
    if (webView != null) {
      webView.reload();
    }
  }

  @Override
  protected void onPause() {
    super.onPause();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (webView != null) {
      if (resultCode == RESULT_OK && data != null) {
        String url = data.getStringExtra("url");
        if (url != null)
          webView.loadUrl(url);
      }
    }
  }

  @Override
  protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
  }

  @Override
  public void onBackPressed() {
    if (webView != null && webView.canGoBack()) {
      webView.goBack();
    } else {
      super.onBackPressed();
      finish();
    }
  }

}

@@ -416,24 +416,49 @@
 .os.Bundle;%0A
+import android.util.Log;%0A
 import andro
@@ -758,16 +758,73 @@
 ivity %7B%0A
+  private static final String TAG = %22KMPBrowserActivity%22;
 %0A  priva
@@ -884,24 +884,29 @@
 _SEARCH_
-BASE_URL
+URL_FORMATSTR
  = %22http
@@ -933,164 +933,134 @@
 ards
-%22;%0A  private static final String KMP_LANGUAGE = %22/languages/%22;%0A  private static final String KMP_QUERY = %22?embed=linux&version=%22; // TODO: Update to Android
+%25s?embed=linux&version=%25s%22; // TODO: Update to Android%0A  private static final String KMP_LANGUAGE_FORMATSTR = %22/languages/%25s%22;
 %0A  p
@@ -2340,73 +2340,164 @@
     
-if (!url.toLowerCase().equals(%22about:blank%22)) %7B%0A          if (url
+String lowerURL = url.toLowerCase();%0A        if (!lowerURL.equals(%22about:blank%22)) %7B%0A          if (lowerURL.startsWith(%22keyman:%22)) %7B%0A            if (lowerURL
 .sta
@@ -2538,16 +2538,18 @@
         
+ 
+ 
 // KMAPr
@@ -2588,16 +2588,18 @@
  intent%0A
+  
         
@@ -2659,19 +2659,24 @@
 i.parse(
-url
+lowerURL
 ));%0A    
@@ -2683,16 +2683,18 @@
         
+  
 startAct
@@ -2726,24 +2726,26 @@
 ;%0A          
+  
 %7D else %7B%0A   
@@ -2757,25 +2757,149 @@
     
-view.loadUrl(url)
+  Log.d(TAG, %22Scheme for %22 + lowerURL + %22 not handled%22);%0A              return true;%0A            %7D%0A          %7D else %7B%0A            return false
 ;%0A  
@@ -3466,16 +3466,8 @@
 mat(
-%22%25s%25s%22, 
 KMP_
@@ -3474,16 +3474,26 @@
 LANGUAGE
+_FORMATSTR
 , langua
@@ -3596,39 +3596,32 @@
 mat(
-%22%25s%25s%25s%25s%22, KMP_SEARCH_BASE_URL
+KMP_SEARCH_URL_FORMATSTR
 , la
@@ -3634,19 +3634,8 @@
 Str,
- KMP_QUERY,
  app

Address review comments