package kr.co.hanwha.hifive.screen.main.setting;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.HashMap;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.base.BaseActivity;
import kr.co.hanwha.hifive.data.source.MemberDataRepository;
import kr.co.hanwha.hifive.dialog.HFSingleDialog;
import kr.co.hanwha.hifive.enums.BaseAnimationType;
import kr.co.hanwha.hifive.enums.BaseToolbarType;
import kr.co.hanwha.hifive.util.HFActivityUtil;
import kr.co.hanwha.hifive.util.HFConstants;
import kr.co.hanwha.hifive.util.HFInfoUtil;

public class MainSettingWebviewActivity extends BaseActivity {
    private WebView mWebView;

    private String mUrl;
    //    private String mEncryption;
    private HashMap<String, String> mHeader;

    @Override
    protected int getContentViewResource() {
        return R.layout.activity_main_setting_webview;
    }

    @Override
    protected BaseToolbarType isToolbarStyle() {
        return BaseToolbarType.ONLY_BACK;
    }

    @Override
    protected BaseAnimationType isShowActivityAnimation() {
        return BaseAnimationType.RIGHT;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mWebView = (WebView) findViewById(R.id.webView);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(new CommonWebViewClient());
        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.addJavascriptInterface(new HFJavaScript(), "Android");

        mWebView.clearHistory();
        mWebView.clearCache(true);
        mWebView.clearView();

        CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();
        cookieSyncManager.sync();

        mUrl = getIntent().getStringExtra(HFActivityUtil.INTENT_URL);

//        mEncryption = MemberDataRepository.getInstance().getEncryptionMemberId();
//        if (TextUtils.isEmpty(mEncryption) == false) {
//            mHeader = new HashMap<>();
//            mHeader.put(HFConstants.HEADER_ENCRYPTION_MEMBER_ID, mEncryption);
//            mHeader.put(HFConstants.HEADER_USER_TYPE, HFInfoUtil.getDepartmentValue(this));
//        }
        String param = "";
        String encryption = MemberDataRepository.getInstance().getEncryptionMemberId();
        if (TextUtils.isEmpty(encryption) == false) {
            param += (TextUtils.isEmpty(param) ? "?" : "&") + HFConstants.HEADER_ENCRYPTION_MEMBER_ID + "=" + encryption;
        }

        String department = HFInfoUtil.getDepartmentValue(this);
        if (TextUtils.isEmpty(department) == false) {
            mHeader = new HashMap<>();
            mHeader.put(HFConstants.HEADER_USER_TYPE, department);
        }

        // Set param
        mUrl += param;

        if (TextUtils.isEmpty(mUrl) == false) {
            if (mUrl.toLowerCase().startsWith("http") == false) mUrl = "http://" + mUrl;

//            /*
            if (mHeader != null)
                mWebView.loadUrl(mUrl, mHeader);
            else
                mWebView.loadUrl(mUrl);
//            */

            /*
            if (mHeader != null) {
                String postData = "";
                for (String key : mHeader.keySet()) {
                    if (TextUtils.isEmpty(postData) == false)
                        postData += "&";
                    postData += key + "=" + mHeader.get(key);
                }
                mWebView.postUrl(mUrl, postData.getBytes());
            } else {
                mWebView.postUrl(mUrl, null);
            }
            */
        } else {
            showAlert(getString(R.string.alert_default_title), getString(R.string.alert_default_message), new HFSingleDialog.OnDialogCallback() {
                @Override
                public void onPositive() {
                    //...
                }
            });
        }
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public void onBackPressed() {
//        if (mWebView.canGoBack())
//            mWebView.goBack();
//        else
        super.onBackPressed();
    }

    /**************************************************
     * WebViewClient
     **************************************************/
    public class CommonWebViewClient extends WebViewClient {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            /*
            if (TextUtils.isEmpty(url) == false && url.equals(mUrl) == false && mHeader != null) {
                String postData = "";
                for (String key : mHeader.keySet()) {
                    if (TextUtils.isEmpty(postData) == false)
                        postData += "&";
                    postData += key + "=" + mHeader.get(key);
                }
                mUrl = url;
                mWebView.postUrl(mUrl, postData.getBytes());
            } else {
                mUrl = url;
                super.onPageStarted(view, url, favicon);
            }
            */
            /*
            if (TextUtils.isEmpty(url) == false && url.equals(mUrl) == false && mHeader != null) {
                mWebView.loadUrl(url, mHeader);
                mUrl = url;
            } else {
                mUrl = url;
                super.onPageStarted(view, url, favicon);
            }
            */
            super.onPageStarted(view, url, favicon);
            showLoadingDialog(true);
        }

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

            showLoadingDialog(false);
//            checkBottomLayout();
        }

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

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            showLoadingDialog(false);
        }
    }

    /**************************************************
     * WebViewClient
     **************************************************/
    public class HFJavaScript {
        public HFJavaScript() {
        }

        @JavascriptInterface
        public void openCustomPopup(String title, String message) {
            showAlert(title, message, new HFSingleDialog.OnDialogCallback() {
                @Override
                public void onPositive() {
                    //...
                }
            });
        }

        @JavascriptInterface
        public void openCustomPopup(String message) {
            showAlert(getString(R.string.alert_default_title), message, new HFSingleDialog.OnDialogCallback() {
                @Override
                public void onPositive() {
                    //...
                }
            });
        }

        @JavascriptInterface
        public void closeWebview() {
            finish();

        }

        @JavascriptInterface
        public void showToast(String type, String content) {

            if (TextUtils.isEmpty(content)) return;
            int icon = 1;
            try {
                icon = Integer.parseInt(type);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (icon == 1)
                showToastAlert(content);
            else if (icon == 2)
                showToastEmpty(content);
            else if (icon == 3)
                showToastConfirm(content);
            else if (icon == 4)
                showToastImpossible(content);
            else
                showToastAlert(content);
        }
    }
}
