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

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.util.ArrayList;

import jp.agentec.abook.abv.bl.acms.client.json.content.ContentJSON;
import jp.agentec.abook.abv.bl.acms.type.DownloadStatusType;
import jp.agentec.abook.abv.bl.common.ABVEnvironment;
import jp.agentec.abook.abv.bl.common.CommonExecutor;
import jp.agentec.abook.abv.bl.common.Constant;
import jp.agentec.abook.abv.bl.common.constant.ABookKeys;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.download.ContentDownloader;
import jp.agentec.abook.abv.bl.download.ContentZipDownloadNotification;
import jp.agentec.abook.abv.cl.util.ContentLogUtil;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.constant.ErrorCode;
import jp.agentec.abook.abv.ui.common.constant.ErrorMessage;
import jp.agentec.abook.abv.ui.common.util.ABVToastUtil;
import jp.agentec.abook.abv.ui.common.view.ABVPopupListWindow;
import jp.agentec.abook.abv.ui.home.helper.ActivityHandlingHelper;
import jp.agentec.abook.abv.ui.viewer.view.CheckFormWebview;

import static jp.agentec.abook.abv.bl.common.constant.ABookKeys.REPORT_START_DATE;
import static jp.agentec.abook.abv.bl.common.constant.ABookKeys.STATUS_CODE;

//TODO: later 遠隔連動関連はContentView,NoPdfViewと共通しているので要集約
public class HTMLWebViewActivity extends ParentWebViewActivity {
    private static final String TAG = "HTMLWebViewActivity";


    /**
     * Called when the activity is first created.
     */
    boolean forwardCheckFlg = false;
    boolean backCheckFlg = false;

    private ImageButton reloadButton;
    private ImageButton downloadButton;
    private int objectLogId;

    private WebView webView;
    private JsInf jsInf = new JsInf();
    private ValueCallback<Uri[]> mUploadMessage;

    private boolean fromDashboard = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Logger.i(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); // タイトルバー非表示
        setContentView(R.layout.ac_html_webview);
        commonOnCreate();
        // ***** 引数の取得
        Intent intent = getIntent();
        if (objectId != -1 || ABVEnvironment.getInstance().disableLogSend) {
            // アクションとして起動された場合, Streaming表示の場合ログは記録しない
            readingLogFlg = false;
        }
        objectLogId = intent.getIntExtra("objectLogId", -1);
        boolean isDownloadable = intent.getBooleanExtra("isDownloadable", false);
        boolean isUpdate = intent.getBooleanExtra("isUpdate", false);

        final String url = intent.getStringExtra("LINKURL"); // LinkURL
        mOperationId = intent.getLongExtra(ABookKeys.OPERATION_ID, -1); // OperationId
        fromDashboard = url.contains("taskKey");

        // ***** WebViewセット

        FrameLayout frameLayout = findViewById(R.id.frameWebView);
        ContextThemeWrapper wrapper = new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);
        // WebView上のIMEキーボード入力をハンドリングするため、カスタムWebViewに変更
        this.webView = new CheckFormWebview(wrapper, new CheckFormWebview.KeyActionCallback() {
            @Override
            public void keyActionCallback(int editorInfoAction) {
                if (editorInfoAction == EditorInfo.IME_ACTION_GO || editorInfoAction == EditorInfo.IME_ACTION_NEXT) {
                    // キーボードの次ボタン検知
                    doEnterEvent();
                }
            }
        });
        frameLayout.addView(webView, new LinearLayout.LayoutParams(FP, FP));
        webView.setVisibility(View.VISIBLE);
        webView.setVerticalScrollbarOverlay(true); // スクロールバー部分の隙間を消す
        if (Logger.isDebugEnabled()) {
            webView.setWebContentsDebuggingEnabled(true); //デバッグモード（chromeからinspect可)
        }
        // webView.setWebViewClient(new WebViewClient());
        // //ブラウザの描画領域を対象としたイベントをフック
        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); // 画面の横幅にページの横幅を合わせる
        //noinspection deprecation(API18から非推奨になった。無視)
        settings.setPluginState(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);
        // webView.loadDataWithBaseURL("", url2, "text/html", "UTF-8", "");
        settings.setAllowFileAccessFromFileURLs(true);  //Android7利用で警告ダイヤログ表示問題対応
        //ターゲットバージョン30以上からデフォルトがfalseに設定されている問題対応
        settings.setAllowFileAccess(true);

        final RelativeLayout fl = (RelativeLayout) findViewById(R.id.frameTopbar);

        // ***** 戻るボタン
        closeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });
        boolean isFromHomeMenu = intent.getIntExtra("pageNumber", -1) == -1;

        if (isFromHomeMenu) {
            // ホームメニューから遷移してきた場合は、closeボタンをホームボタンに差替え
            closeButton.setBackgroundResource(R.drawable.btn_home);
            historyListBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    showHistoryList(v);
                }
            });

            subMenuBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    mShowedPopupWindow = new ABVPopupListWindow(HTMLWebViewActivity.this);
                    if (isNormalSize()) {
                        mShowedPopupWindow.setWidth(getRDimensionSize(R.dimen.popup_size_normal));
                    } else {
                        mShowedPopupWindow.setWidth(getRDimensionSize(R.dimen.popup_size_large));
                    }

                    ArrayList<String> menuNameList = new ArrayList<>();
                    final boolean isExist = contentLogic.isExsitContentFavorite(getContentId());
                    if (isExist) {
                        menuNameList.add(getRString(R.string.remove_favorite_content));
                    } else {
                        menuNameList.add(getRString(R.string.add_favorite_content));
                    }

                    mShowedPopupWindow.setRepresentNames(menuNameList);
                    mShowedPopupWindow.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            switch (position) {
                                case 0:
                                    // お気に入り
                                    contentLogic.setFavoriteContent(getContentId(), !isExist);
                                    break;
                                default:
                                    break;
                            }
                            mShowedPopupWindow.dismiss();
                        }
                    });

                    mShowedPopupWindow.showAsDropDown(v);
                }
            });

        } else {
            historyListBtn.setVisibility(View.GONE);
            subMenuBtn.setVisibility(View.GONE);
        }

        // ***** リンク元コンテンツへ戻るボタン
        btnLinkOriginalBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToBack();
            }
        });
        subMenuBtn.setVisibility(View.GONE);

        btnWebClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (fl.getVisibility() == View.VISIBLE) {
                    fl.setVisibility(View.GONE);
                    //noinspection deprecation(API16から非推奨になった。無視)
                    btnWebClose.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_webview_open));
                } else {
                    fl.setVisibility(View.VISIBLE);
                    //noinspection deprecation(API16から非推奨になった。無視)
                    btnWebClose.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_webview_close));
                }
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                commonProgressChanged(newProgress);
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                             FileChooserParams fileChooserParams) {
                boolean result = false;
                if (fileChooserParams.getAcceptTypes()[0].toLowerCase().indexOf(ABookKeys.IMAGE) != -1) {
                    result = startCameraIntent(ABOOK_CHECK_TASK_IMAGE, "Camera", ABookKeys.IMAGE, true);

                } else if (fileChooserParams.getAcceptTypes()[0].toLowerCase().indexOf(ABookKeys.VIDEO) != -1) {
                    result = startCameraIntent(ABOOK_CHECK_TASK_VIDEO, "Video", ABookKeys.VIDEO, true);
                }

                if (result) {
                    if (mUploadMessage != null) {
                        mUploadMessage.onReceiveValue(null);
                    }
                    mUploadMessage = filePathCallback;
                }
                Logger.i(TAG, "oepnFile acceptType : %s", fileChooserParams.getAcceptTypes()[0]);
                return result;
            }
        });

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, final String url) {
                if (mXWalkOpenType == Constant.XWalkOpenType.PANO_EDIT) {
                    // 360編集画面時に以下の処理でステータスコードのチェックを行う
                    if (!url.contains("%")) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                HttpGet httpGet = new HttpGet(url);
                                HttpResponse response;
                                HttpClient client = new DefaultHttpClient();
                                try {
                                    response = client.execute(httpGet);
                                    final int statusCode = response.getStatusLine().getStatusCode();
                                    Logger.d("shouldInterceptRequest url :" + url + "   status code : " + statusCode);
                                    if (statusCode >= 400) {
                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                commonOnReceivedResponseHeaders(url, statusCode);
                                            }
                                        });
                                    }
                                } catch (IOException e) {
                                    Logger.e(TAG, e);
                                }
                            }
                        }).start();
                    }
                }
                return null;
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                backCheckFlg = view.canGoBack();
                forwardCheckFlg = view.canGoForward();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Logger.e(TAG, "onReceivedError errorCode=%s, description=%s, failingUrl=%s", errorCode, description, failingUrl);
            }

            @Override
            public void onPageFinished(final WebView view, String url) {
                super.onPageFinished(webView, url);

                if (backCheckFlg) {
                    btnWebBack.setEnabled(true);
                    btnWebBack.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            view.goBack();
                        }
                    });
                } else {
                    btnWebBack.setEnabled(false);
                }

                if (forwardCheckFlg) {
                    btnWebForward.setEnabled(true);
                    btnWebForward.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            view.goForward();
                        }
                    });
                } else {
                    btnWebForward.setEnabled(false);
                }
                isPageFinished = true;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Logger.v(TAG, "shouldOverrideUrlLoading: %s", url);

                if (url.startsWith("abook")) {
                    final Uri uri = Uri.parse(url);
                    // AndroidOSが5以下のPANO_SERVER処理のため、置き換える必要がある。
                    url = "/" + url;
                    if (url.contains(ABookKeys.ABOOK_CHECK_API)) {
                        String cmd = uri.getQueryParameter(ABookKeys.CMD);
                        if (cmd.contains(ABookKeys.CMD_LOCK_REPORT)) {
                            String sd = uri.getQueryParameter(REPORT_START_DATE);
                            Logger.d(TAG, "mCmd:" + cmd + ",reportStartDate: "+ sd+", CheckApiUrl: " + url);
                        } else {
                            Logger.d(TAG, "mCmd:" + cmd + ", CheckApiUrl: " + url);
                        }
                        commonShouldOverrideUrlLoading(uri, null);
                    }
                    if (fromDashboard && (url.contains(ABookKeys.CMD_CANCEL_TASK_REPORT))) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                finishActivity();
                            }
                        });
                    }
                    return true;
                }
                return false;
            }

        });
        if (mXWalkOpenType == Constant.XWalkOpenType.TASK_REPORT) {
            webView.addJavascriptInterface(jsInf, "android");
        }
        Logger.d(TAG, "loadUrl: " + url);
        webView.loadUrl(url);

        reloadButton = (ImageButton) findViewById(R.id.btn_reload);
        reloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Logger.d(TAG, "ReloadUrl");
                if (latitude != null && longitude != null) {
                    webView.loadUrl(url + "&reload=true&latitude=" + latitude + "&longitude=" + longitude);
                } else {
                    webView.loadUrl(url + "&reload=true");
                }
            }
        });

        downloadButton = (ImageButton) findViewById(R.id.btn_download);
        downloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Logger.d(TAG, "Click download");
                try {
                    downloadButton.setEnabled(false);
                    ContentDownloader.getInstance().download(contentId);
                    ABVToastUtil.showMakeText(getApplicationContext(), R.string.download_start, Toast.LENGTH_SHORT);
                } catch (Exception e) {
                    Logger.e(TAG, "Download failed.", e);
                    downloadButton.setEnabled(true);
                    handleErrorMessageToast(e);
                }
            }
        });
        if (isDownloadable) {
            downloadButton.setVisibility(View.VISIBLE);
            if (isUpdate) {
                downloadButton.setBackgroundResource(R.drawable.btn_update);
            } else {
                downloadButton.setBackgroundResource(R.drawable.btn_download);
            }
        }


        mBtnRemoteStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                meetingManager.setPaused(false);
                configureRemote();
            }
        });

        exitMeetingBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Logger.v(TAG, "exit onClick");
                showMeetingExitDialog();
            }
        });

        promoteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Logger.v(TAG, "promote onClick");
                sendPromoteRequest();
            }
        });

        pauseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Logger.v(TAG, "remoteOnOff onClick");
                meetingManager.setPaused(true);
                configureRemote();
            }
        });

        historyListBtn.setVisibility(View.GONE);

        if (isLinkedContent) {
            if (ContentJSON.KEY_MOVIE_TYPE.equals(mContentDto.contentType) || ContentJSON.KEY_MUSIC_TYPE.equals(mContentDto.contentType)
                    || ContentJSON.KEY_PANO_IMAGE_TYPE.equals(mContentDto.contentType) || ContentJSON.KEY_PANO_MOVIE_TYPE.equals(mContentDto.contentType)
                    || ContentJSON.KEY_OBJECTVR_TYPE.equals(mContentDto.contentType) || ContentJSON.KEY_OTHER_TYPE.equals(mContentDto.contentType)) {

                closeButton.setBackgroundResource(R.drawable.btn_first_back);
                btnLinkOriginalBack.setVisibility(View.VISIBLE);
                btnWebBack.setVisibility(View.GONE);
                btnWebForward.setVisibility(View.GONE);
                reloadButton.setVisibility(View.GONE);
                downloadButton.setVisibility(View.GONE);
                mBtnRemoteStart.setVisibility(View.GONE);
                exitMeetingBtn.setVisibility(View.GONE);
                promoteBtn.setVisibility(View.GONE);
                pauseBtn.setVisibility(View.GONE);
                historyListBtn.setVisibility(View.GONE);
                subMenuBtn.setVisibility(View.GONE);
            } else if (ContentJSON.KEY_LINK_TYPE.equals(mContentDto.contentType) || ContentJSON.KEY_HTML_TYPE.equals(mContentDto.contentType)) {
                closeButton.setBackgroundResource(R.drawable.btn_first_back);
                btnLinkOriginalBack.setVisibility(View.VISIBLE);
                reloadButton.setVisibility(View.GONE);
                downloadButton.setVisibility(View.GONE);
                mBtnRemoteStart.setVisibility(View.GONE);
                exitMeetingBtn.setVisibility(View.GONE);
                promoteBtn.setVisibility(View.GONE);
                pauseBtn.setVisibility(View.GONE);
                historyListBtn.setVisibility(View.GONE);
                subMenuBtn.setVisibility(View.GONE);
            }
        } else {
            configureRemote();
        }

    }

    private class JsInf {
        @JavascriptInterface
        public void existSetLocation(String ret) {
            Logger.d(TAG, "existSetLocation=%s", ret);
            if (ret != null && ret.equals("true")) { // setLocationメソッドが存在する場合、ページ読み込み完了とみなす
                isPageFinished = true;
            } else { // 存在しない場合、ページ読み込み未完了とみなし１秒後に再度呼出しを繰り返す
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        callExistsSetLocation();
                    }
                }, 1000);
            }
        }

        @JavascriptInterface
        public void existSendLog(String ret) {
            Logger.d(TAG, "existSendLog=%s", ret);
            if (ret != null && ret.equals("true")) {
                runOnUiThread(new Runnable() { // sendLogメソッドが存在する場合、呼び出す
                    @Override
                    public void run() {
                        try {
                            webView.loadUrl("javascript:sendLog()");
                        } catch (Exception e) {
                            Logger.e(TAG, "javascript:sendLog error. " + e.toString());
                        }
                    }
                });
            } else {
                finishActivity();
            }
        }

        @JavascriptInterface
        public void getAttachedDataUrl(String taskKey, String data) {
            commonAttachedDataUrl(taskKey, data);
        }
    }

    @Override
    protected void onDestroy() {
        Logger.d(TAG, "onDestroy");
        finishWebView();
        super.onDestroy();
    }

    public void finishWebView() {
        CommonExecutor.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    if (isPageFinished) {
                        break;
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                    }
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (webView != null) {
                            ViewGroup parent = (ViewGroup) webView.getParent();
                            if (parent != null) {
                                parent.removeView(webView);
                            }
                            webView.removeAllViews();
                            webView.destroy();
                            webView = null;
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onDetachedFromWindow() {
        Logger.d(TAG, "onDetachedFromWindow");
        super.onDetachedFromWindow();
        finishWebView();
    }


    @Override
    protected void finishActivity() {
        setResult(RESULT_OK, new Intent());
        finish();
        if (objectId == -1) { // HTMLコンテンツの場合で、KeyUpではない場合、全コンテンツActivityを終了
            if (isLinkedContent) {
                ActivityHandlingHelper.getInstance().finishAllLinkContentViewActivity();
            } else {
                ActivityHandlingHelper.getInstance().finishAllContentViewActivity();

            }
        }
    }

    @Override
    public void onResume() {
        Logger.i(TAG, "onResume");
        super.onResume();
        if (objectLogId != -1) {
            ContentLogUtil.getInstance().resumeObjectLog(getContentId(), objectLogId);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        webView.stopLoading();
        if (objectLogId != -1) {
            ContentLogUtil.getInstance().endObjectLog(getContentId(), objectLogId);
        }
    }

    @Override
    public void configureRemote() {
        if (objectId == -1 && meetingManager.isSubscribed()) {
            closeButton.setVisibility(View.INVISIBLE);
            historyListBtn.setVisibility(View.INVISIBLE);
            if (meetingManager.isPaused()) {
                mBtnRemoteStart.setVisibility(View.VISIBLE);
                pauseBtn.setVisibility(View.GONE);
                exitMeetingBtn.setVisibility(View.GONE);
                promoteBtn.setVisibility(View.GONE);
            } else {
                subMenuBtn.setVisibility(View.GONE);
                mBtnRemoteStart.setVisibility(View.GONE);
                pauseBtn.setVisibility(View.VISIBLE);
                exitMeetingBtn.setVisibility(View.VISIBLE);
                promoteBtn.setVisibility(View.VISIBLE);
            }
        } else {
            closeButton.setVisibility(View.VISIBLE);
            historyListBtn.setVisibility(View.GONE);
            subMenuBtn.setVisibility(View.GONE);
            mBtnRemoteStart.setVisibility(View.GONE);
            if (meetingManager.isSendable()) { // 会議室退室ボタン表示
                exitMeetingBtn.setVisibility(View.VISIBLE);
            }
            pauseBtn.setVisibility(View.GONE);
            promoteBtn.setVisibility(View.GONE);
        }

        if (meetingManager.isConnected() && meetingManager.isOwner()) {
            webView.setOnTouchListener(new OnTouchListener() {
                boolean showCount = false;

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    Logger.d(TAG, "onTouch showCount=" + showCount);
                    showCount = !showCount;
                    setMeetingParticipantCount(showCount, findViewById(android.R.id.content));
                    v.performClick();
                    return false;
                }
            });
        }
        commonConfigureRemote();
    }

    @Override
    public void onDownloadingContentZip(final ContentZipDownloadNotification notification) { // Streaming表示でダウンロードが完了した場合
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (notification.getDownloadStatus() == DownloadStatusType.Downloading) {
                    Logger.d(TAG, "onDownloadingContentZip .....................Downloading......................>");
                    ABVToastUtil.showMakeText(getApplicationContext(), R.string.reader_downloading, Toast.LENGTH_SHORT);
                } else if (notification.getDownloadStatus() == DownloadStatusType.Initializing) {
                    Logger.d(TAG, "onDownloadingContentZip ..........................Initializing.................>");
                    ABVToastUtil.showMakeText(getApplicationContext(), R.string.initializing, Toast.LENGTH_SHORT);
                } else if (notification.getDownloadStatus() == DownloadStatusType.Succeeded) {
                    Logger.d(TAG, "onDownloadingContentZip .........................Succeeded..................>");
                    ABVToastUtil.showMakeText(getApplicationContext(), R.string.download_success, Toast.LENGTH_SHORT);
                }
                downloadButton.setVisibility(View.GONE);
            }
        });
    }

    private void callExistsSetLocation() { // setLocation functionがjavascriptに定義されているかどうかを調べる（結果はexistSetLocationメソッドにコールバック）
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (webView != null) {
                    webView.loadUrl("javascript:android.existSetLocation(typeof setLocation == 'function')");
                }
            }
        });
    }

    @Override
    protected void webViewLoadUrl(String url) {
        if (webView != null) {
            webView.loadUrl(url);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Uri[] result = null;
        Uri dataUri = null;
        if (intent != null && resultCode == RESULT_OK) {
            String dataString = intent.getDataString();
            if (dataString != null) {
                dataUri = Uri.parse(dataString);
                result = new Uri[]{dataUri};
            }
        }

        if (requestCode == ABOOK_CHECK_TASK_IMAGE) {
            if (mUploadMessage == null) {
                return;
            }
            // 画像
            try {
                if (dataUri == null) {
                    dataUri = imageUri;
                }
                Uri responseUri = attachmentImageProcessing(dataUri);
                if (responseUri != null) {
                    mUploadMessage.onReceiveValue(new Uri[]{responseUri});
                } else {
                    mUploadMessage.onReceiveValue(null);
                }
            } catch (Exception e) {
                Logger.e(TAG, e);
                mUploadMessage.onReceiveValue(null);
                ErrorMessage.showErrorMessageToast(getApplicationContext(), ErrorCode.E107);
            }
        } else if (requestCode == ABOOK_CHECK_TASK_VIDEO) {
            if (mUploadMessage == null) {
                return;
            }
            mUploadMessage.onReceiveValue(result);
        } else if (requestCode == ABOOK_CHECK_SELECT_SCENE) {
            if (intent != null && result != null) {
                confirmEntrySceneDialog(result[0]);
            }
        }
        mUploadMessage = null;
    }
}
