package jp.agentec.abook.abv.ui.viewer.activity;

import android.app.DownloadManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebBackForwardList;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;

import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.OnlineHTMLWebViewLogic;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.activity.ABVContentViewActivity;

/**
 * Created by ogawa-y on 2020/06/22.
 */
public class OnlineHTMLWebViewActivity extends ABVContentViewActivity {
    private static final String TAG = "OnlineHTMLWebView";
    private WebView webView;

    private Button closeButton;
    private ImageButton backButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Logger.i(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); // タイトルバー非表示
        setContentView(R.layout.ac_online_html_webview);

        TextView title = findViewById(R.id.title);
        title.setText(R.string.title_quick_report_output);

        setWebView();

        // 引継ぎパラメータ
        Intent intent = getIntent();
        final String url = intent.getStringExtra("LINKURL"); // LinkURL
        final Long operaitonId = intent.getLongExtra("operationId", -1);
        Map<String, String> param = new HashMap<>();
        if (operaitonId != -1) {
            param.put("operationId", operaitonId.toString());
        }
        Logger.d(TAG,"LINKURL=" + url);
        OnlineHTMLWebViewLogic logic = AbstractLogic.getLogic(OnlineHTMLWebViewLogic.class);
        webView.postUrl(url, logic.getPostData(param));

        // ***** 閉じるボタン
        closeButton = findViewById(R.id.closeBtn);
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });

        // ***** 戻るボタン
        backButton = findViewById(R.id.backBtn);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // PDFダウンロードの場合はスキップする
                WebBackForwardList bfList = webView.copyBackForwardList();
                for (int i = 0, len = bfList.getCurrentIndex(); i < len; i++) {
                    String url = bfList.getItemAtIndex(len - i).getUrl();
                    if (url.contains("fileSelect")) {
                        continue;
                    }
                    if (webView.canGoBackOrForward(-1 * (i + 1))) {
                        webView.goBackOrForward(-1 * (i + 1));
                        break;
                    }
                }
            }
        });
    }

    private void setWebView() {
        webView = findViewById(R.id.webView);
        webView.setVisibility(View.VISIBLE);
        webView.setVerticalScrollbarOverlay(true); // スクロールバー部分の隙間を消す
        if (Logger.isDebugEnabled()) {
            webView.setWebContentsDebuggingEnabled(true); //デバッグモード（chromeからinspect可)
        }

        // //ブラウザの描画領域を対象としたイベントをフック
        WebSettings settings = webView.getSettings();
        settings.setSupportMultipleWindows(true); // 新しいウィンドウを開くイベントを取得する
        settings.setLoadsImagesAutomatically(true); // イメージを自動的にロードする
        settings.setBuiltInZoomControls(true); // ズーム機能を有効にする
        settings.setSupportZoom(true); // ズーム機能を有効にする
        settings.setJavaScriptEnabled(true); // JavaScriptを有効にする
        settings.setLoadWithOverviewMode(true); // 画面の横幅にページの横幅を合わせる
        settings.setUseWideViewPort(true); // 画面の横幅にページの横幅を合わせる
        settings.setPluginState(WebSettings.PluginState.ON); // 「EventHub.removeMessages(int what = 107) is not supported before the WebViewCore is set up.」のエラー対応（あまり効果ない？）
        settings.setDomStorageEnabled(true); // WebStorage有効化
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAllowFileAccessFromFileURLs(true);  //Android7利用で警告ダイヤログ表示問題対応
        //ターゲットバージョン30以上からデフォルトがfalseに設定されている問題対応
        settings.setAllowFileAccess(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Logger.v(TAG, "shouldOverrideUrlLoading: %s", url);
                return false;
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                // ***** 戻るボタンの活性制御
                backButton.setEnabled(webView.canGoBack());
                super.onPageFinished(view, url);
            }
        });

        webView.setDownloadListener(new DownloadListener() {

            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(
                        Uri.parse(url));

                final String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
                request.setMimeType(mimetype);
                //------------------------COOKIE!!------------------------
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                //------------------------COOKIE!!------------------------
                request.addRequestHeader("User-Agent", userAgent);
                request.setTitle(fileName);
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                if (dm != null) {
                    dm.enqueue(request);
                }
                Toast.makeText(getApplicationContext(), getString(R.string.download_start), //To notify the Client that the file is being downloaded
                        Toast.LENGTH_LONG).show();

            }
        });
    }

    @Override
    protected void finishActivity() {
        setResult(RESULT_OK, new Intent());
        finish();
    }
}
