package com.gh.gamecenter.geetest;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gh.gamecenter.common.exposure.meta.MetaUtil;
import com.lightgame.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

/**
 * 验证对话框
 *
 * @author dreamzsm@gmail.com
 */
class GtDialog extends Dialog {

    private String baseURL = "https://static.geetest.com/static/appweb/app-index.html";
    private String mParamsString;
    private String product = "embed";
    private String language = "zh-cn";
    private String mTitle = "";
    private Boolean debug = false;
    private int mWidth;
    private int mHeight;
    private GTWebView mGTWebView;
    private GtListener mGtListener;

    GtDialog(Context context, JSONObject params) {
        super(context);
        mParamsString = unwrappingParameters(params);
        init();
    }

    void setGtListener(GtListener gtListener) {
        mGtListener = gtListener;
    }

    private String unwrappingParameters(JSONObject params) {
        Iterator<String> iter = params.keys();
        StringBuilder paramString = new StringBuilder();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                if (iter.hasNext()) {
                    paramString.append(key).append("=").append(params.getString(key)).append("&");
                } else {
                    paramString.append(key).append("=").append(params.getString(key));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return paramString.toString();
    }

    public void init() {
        mWidth = getDeviceWidth();
        mHeight = getDeviceHeight();

        mGTWebView = new GTWebView(getContext());
        mGTWebView.setGtWebViewListener(new GtWebViewListener() {
            @Override
            public void gtCallReady(Boolean status) {
                if (mGtListener != null) {
                    mGtListener.gtCallReady(status);
                }
            }

            @Override
            public void gtError() {
                if (mGtListener != null) {
                    mGtListener.gtError();
                }
            }
        });
        mGTWebView.init();

        GtJSInterface gtJSInterface = new GtJSInterface();
        gtJSInterface.setGtListener(mGtListener);

        mGTWebView.addJavascriptInterface(gtJSInterface, "JSInterface");

        String pathUrl = getPathUrl(mParamsString);
        String gt_mobile_req_url = baseURL + pathUrl;
        Utils.log("验证模块拼接后的url: " + gt_mobile_req_url);
        mGTWebView.loadUrl(gt_mobile_req_url);
        mGTWebView.buildLayer();
    }

    private String getPathUrl(String paramsString) {
        float scale = getDeviceScale();
        return "?" + paramsString
//                + "&challenge=" + this.challenge
//                + "&success=" + (this.success ? 1 : 0)
                + "&jnfj=" + MetaUtil.getBase64EncodedIMEI()
                + "&mType=" + Build.MODEL
                + "&osType=" + "android"
                + "&osVerInt=" + Build.VERSION.RELEASE
                + "&gsdkVerCode=" + "2.16.12.15.1"
                + "&title=" + this.mTitle //验证标题，不宜过长
                + "&lang=" + this.language //支持"zh-cn","zh-hk","zh-tw","ko-kr","ja-jp","en-us".默认"zh-cn"
                + "&debug=" + this.debug
                + "&width=" + (int) (mWidth / scale + 1.5f);//1.5f: fix blank on the webview
    }

    private int getDeviceWidth() {
        int height = DimenTool.getHeightPx(getContext());
        int width = DimenTool.getWidthPx(getContext());
        float scale = getDeviceScale();

        final int WIDTH = 290;

        if (height < width) {
            width = height * 3 / 4;
        }
        width = width * 4 / 5;
        if ((int) (width / scale + 0.5f) < WIDTH) {
            width = (int) ((WIDTH - 0.5f) * scale);
        }
        return width;
    }

    private int getDeviceHeight() {
//        int height = DimenTool.getHeightPx(getContext());
//        int width = DimenTool.getWidthPx(getContext());
        float scale = getContext().getResources().getDisplayMetrics().density;

        final int HEIGHT = 500;

        return (int) (HEIGHT * scale);
    }

    private float getDeviceScale() {
        return getContext().getResources().getDisplayMetrics().density;
    }

    public void setBaseURL(String url) {
        this.baseURL = url;
    }

    public void setDebug(Boolean debug) {
        this.debug = debug;
    }

    public void setProduct(String product) {
        this.product = product;
    }

    //支持"zh-cn","zh-hk","zh-tw","ko-kr","ja-jp","en-us".默认"zh-cn".
    public void setLanguage(String lang) {
        this.language = lang;
    }

    //验证标题, 默认无标题, 不宜过长.
    public void setGTTitle(String title) {
        this.mTitle = title;
    }

    public void stopLoading() {
        mGTWebView.stopLoading();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        RelativeLayout contentView = new RelativeLayout(getContext());

        contentView.addView(mGTWebView);
        TextView textView = new TextView(getContext());
        textView.setBackgroundColor(Color.WHITE);
        textView.setGravity(Gravity.CENTER);
        textView.setText("完成验证即可领取礼包");
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(getDeviceWidth(), (int) ((float) getDeviceWidth() / 7.5));
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        contentView.addView(textView, params);

        setContentView(contentView);

        final LayoutParams layoutParams = mGTWebView.getLayoutParams();

        layoutParams.width = mWidth;
        layoutParams.height = LayoutParams.WRAP_CONTENT;
        mGTWebView.setLayoutParams(layoutParams);

        LayoutParams contentViewParams = contentView.getLayoutParams();
        contentViewParams.height = (int) ((float) getDeviceWidth() * 0.97);
        contentViewParams.width = getDeviceWidth();
        contentView.setLayoutParams(contentViewParams);
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mGTWebView.stopLoading();
        mGTWebView.removeJavascriptInterface("JSInterface");
        mGTWebView.removeAllViews();
        mGTWebView.destroy();
    }

}
