package info.burguillos.bi;

import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebResourceRequest;
import android.webkit.JavascriptInterface;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.util.Log;
import android.os.Message;
import android.os.Handler;
import android.os.Looper;

import android.view.ViewTreeObserver;
import android.view.MotionEvent;
import android.view.MenuItem;
import android.view.Menu;
import android.content.Intent;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.app.PendingIntent;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.view.View;
import android.net.Uri;
import android.widget.RelativeLayout;
import android.content.pm.ShortcutInfo;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;
import android.graphics.drawable.Icon;
import java.io.InputStream;
import java.net.URL;
import android.content.pm.ApplicationInfo;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.FrameLayout;
import android.util.DisplayMetrics;
import android.view.ContextMenu;
import android.view.MenuInflater;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.content.pm.ShortcutManager;


class MenuId {
    public static final int OPEN_LINK = 0;
    public static final int OPEN_LINK_BROWSER = 1;
    public static final int COPY_LINK = 2;
    public static final int OPEN_IMAGE_BROWSER = 4;
    public static final int COPY_IMAGE_URL = 5;
    public static final int COPY_TEXT = 6;
};

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RelativeLayout relativeLayout;
    String baseUrl;

    String hrefContextMenu = null;
    String srcContextMenu = null;
    String titleContextMenu = null;

    class WebCallsAndroidCode {
        @JavascriptInterface
        public void openInBrowser(String url) {
            Uri targetUri = Uri.parse(url);

            Intent emptyBrowserIntent = new Intent();
            emptyBrowserIntent.setAction(Intent.ACTION_VIEW);
            emptyBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            emptyBrowserIntent.setData(Uri.fromParts("http", "", null));

            Intent targetIntent = new Intent();
            targetIntent.setAction(Intent.ACTION_VIEW);
            targetIntent.addCategory(Intent.CATEGORY_BROWSABLE);
            targetIntent.setData(targetUri);
            targetIntent.setSelector(emptyBrowserIntent);

            startActivity(targetIntent);
        }

        @JavascriptInterface
        public void pinPage(String url, String shortLabel, String iconUrl) {
            ShortcutManager shortcutManager =
                MainActivity.this.getSystemService(ShortcutManager.class);
            if (!shortcutManager.isRequestPinShortcutSupported()) {
                Log.w("BurguillosInfo", "Unable to pin.");
                return;
            }
            Intent targetIntent = new Intent(MainActivity.this.getApplicationContext(), MainActivity.class);
            targetIntent.setAction(Intent.ACTION_VIEW);
            targetIntent.putExtra("url", url);
            Log.w("BurguillosInfo", "Created intent " + url + " " + shortLabel);

            Bitmap bitmapIcon = getBitmap(iconUrl);
            if (bitmapIcon == null) {
                Log.w("BurguillosInfo", "No bitmap.");
            }
            ShortcutInfo pinShortcutInfo =
                new ShortcutInfo.Builder(MainActivity.this, url)
            .setShortLabel(shortLabel)
            .setIntent(targetIntent)
            .setIcon(Icon.createWithBitmap(getBitmap(iconUrl)))
            .build();
            Log.w("BurguillosInfo", "Built pin.");

            shortcutManager.requestPinShortcut(pinShortcutInfo, null);
            Log.w("BurguillosInfo", "added request pin.");
        }
    }
    @Override
    public boolean onContextItemSelected (MenuItem item) {
        final int id = item.getItemId();
        ClipData clip = null;
        ClipboardManager clipboard = (ClipboardManager) getSystemService(this.CLIPBOARD_SERVICE);
        Intent targetIntent = null;
        Uri targetUri = null;
        switch (id) {
        case MenuId.OPEN_LINK:
            targetUri = Uri.parse(hrefContextMenu);
            targetIntent = new Intent();
            targetIntent.setAction(Intent.ACTION_VIEW);
            targetIntent.setData(targetUri);
            startActivity(targetIntent);
            break;
        case MenuId.OPEN_LINK_BROWSER:
            new WebCallsAndroidCode().openInBrowser(hrefContextMenu);
            break;
        case MenuId.COPY_LINK:
            clip = ClipData.newPlainText(hrefContextMenu, hrefContextMenu);
            clipboard.setPrimaryClip(clip);
            break;
        case MenuId.OPEN_IMAGE_BROWSER:
            new WebCallsAndroidCode().openInBrowser(srcContextMenu);
            break;
        case MenuId.COPY_IMAGE_URL:
            clip = ClipData.newPlainText(srcContextMenu, srcContextMenu);
            clipboard.setPrimaryClip(clip);
            break;
        case MenuId.COPY_TEXT:
            clip = ClipData.newPlainText(titleContextMenu, titleContextMenu);
            clipboard.setPrimaryClip(clip);
            break;
        default:
            Log.w("BurguillosInfo", "No recognized id in context menu.");
        }
        return false;
    }

    private static Bitmap getBitmap(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            Bitmap d = BitmapFactory.decodeStream(is);
            is.close();
            return d;
        } catch (Exception e) {
            Log.w("BurguillosInfo", e);
            return null;
        }
    }

    public boolean onLongClick(View v) {
        return false;
    }

    @Override
    public void onCreateContextMenu (ContextMenu menu,
                                     View v,
                                     ContextMenu.ContextMenuInfo menuinfo) {
        Log.w("BurguillosInfo", baseUrl);
        new MenuInflater(MainActivity.this).inflate(R.menu.long_click_webview, menu);
        if (hrefContextMenu != null) {
            menu.add(Menu.NONE, MenuId.OPEN_LINK, Menu.NONE, "Abrir enlace.");
            menu.add(Menu.NONE, MenuId.OPEN_LINK_BROWSER, Menu.NONE, "Abrir enlace en el navegador.");
            menu.add(Menu.NONE, MenuId.COPY_LINK, Menu.NONE, "Copiar enlace.");
        }
        if (srcContextMenu != null) {
            menu.add(Menu.NONE, MenuId.OPEN_IMAGE_BROWSER, Menu.NONE, "Abrir imagen en el navegador.");
            menu.add(Menu.NONE, MenuId.COPY_IMAGE_URL, Menu.NONE, "Copiar enlace de la imagen.");
        }
        if (titleContextMenu != null) {
            menu.add(Menu.NONE, MenuId.COPY_TEXT, Menu.NONE, "Copiar texto del enlace.");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseUrl = getResources().getString(R.string.baseUrl);

        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.web);
        Looper looper = Looper.getMainLooper();
        final Handler handler = new Handler(looper) {
            @Override
            public void handleMessage(Message message) {
                Bundle bundle = message.getData();

                for (String key: bundle.keySet())
                {
                    Log.w ("BurguillosInfo", key + " is a key in the bundle");
                }
                srcContextMenu = null;
                hrefContextMenu = null;
                titleContextMenu = null;
                CharSequence value = bundle.getCharSequence("src");
                if (value != null) {
                    srcContextMenu = value + "";
                }
                value = bundle.getCharSequence("url");
                if (value != null) {
                    hrefContextMenu = value + "";
                }
                value = bundle.getCharSequence("title");
                if (value != null) {
                    titleContextMenu = value + "";
                }
                MainActivity.this.registerForContextMenu(webView);
                MainActivity.this.openContextMenu(webView);
                MainActivity.this.unregisterForContextMenu(webView);
            }
        };


        webView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                WebView.HitTestResult hit = webView.getHitTestResult();
                if (hit == null
                        || hit.getType() == WebView.HitTestResult.UNKNOWN_TYPE
                        || hit.getType() == WebView.HitTestResult.EDIT_TEXT_TYPE) {
                    return false;
                }
                Log.w("BurguillosInfo", hit.getType()+"");
                Message message = handler.obtainMessage();
                webView.requestFocusNodeHref(message);
                return true;
            }
        });
        swipeRefreshLayout = findViewById(R.id.swipeContainer);
        relativeLayout = findViewById(R.id.relative);
        swipeRefreshLayout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.reload();
            }
        });

        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                final int action = event.getAction() & MotionEvent.ACTION_MASK;
                if (action != MotionEvent.ACTION_DOWN) {
                    return false;
                }
                if (event.getY() > 100) {
                    swipeRefreshLayout.setEnabled(false);
                    return false;
                }
                swipeRefreshLayout.setEnabled(true);
                return false;
            }
        });


        webView.addJavascriptInterface(new WebCallsAndroidCode(), "Android");
        Intent resultIntent = getIntent();

        String url = baseUrl;
        url = getCorrectUrlForIntent(resultIntent, url);

        webView.loadUrl(url);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        if (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)) {
            webView.setWebContentsDebuggingEnabled(true);
        }

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.w("BurguillosInfo", consoleMessage.message() + " -- From line " +
                      consoleMessage.lineNumber() + " of " + consoleMessage.sourceId());
                return true;
            }
        });

        webView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                swipeRefreshLayout.setRefreshing(false);
            }

            public void onPageStarted(WebView view, String url) {
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,
                                                    WebResourceRequest request) {
                Uri uri = request.getUrl();
                if (!uri.toString().startsWith(baseUrl) && !uri.toString().startsWith("/")) {
                    final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                    return true;
                }
                return false;
            }
        });
    }

    protected void onNewIntent(Intent resultIntent) {
        super.onNewIntent(resultIntent);
        String url = baseUrl;
        url = getCorrectUrlForIntent(resultIntent, url);
        webView.loadUrl(url);
    }

    public static String getCorrectUrlForIntent(Intent resultIntent, String url) {
        Bundle extras = resultIntent.getExtras();
        if(extras != null)
        {
            String paramURL = extras.getString("url");
            if (paramURL != null) {
                return url + paramURL;
            }
        }
        Uri possibleUri = resultIntent.getData();
        if (possibleUri== null) {
            return url;
        }
        String possibleUrl = possibleUri.toString();
        if (possibleUrl.startsWith("http")) {
            return possibleUrl;
        }
        Log.w("BurguillosInfo", url);
        return url;
    }

    @Override
    public void onBackPressed() {
        WebView webView = findViewById(R.id.web);
        if (webView.canGoBack()) {
            webView.goBack();
            return;
        }
        super.onBackPressed();
    }
}
