package com.wasu.cs.widget.mediacontrol;

/**
 * Created by zhangrm on 16-3-21.
 */

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Build;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.JavascriptInterface;

import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.IAuthInterface;
import com.wasu.comp.wasuwebview.WasuWebView;
import com.wasu.compfactory.WasuCompFactory;
import com.wasu.cs.jsobject.WR;
import com.wasu.cs.jsobject.WR_Favorites;
import com.wasu.cs.jsobject.WR_History;
import com.wasu.cs.jsobject.WR_Term;
import com.wasu.cs.jsobject.WR_UserCenter;
import com.wasu.cs.jsobject.tv;
import com.wasu.module.log.WLog;
import com.wasu.util.SystemUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DialogPlanBuy extends Dialog {
    private static final String tag = "DialogPlanBuy";

    public static final int PAY_STATUS_OK = 0;
    public static final int PAY_STATUS_FAILED = 1;

    private WasuWebView mWebView;

    ////////////////////////////////////////////////////////////////////////////////////////////////

    private String pageUrl;
    private String channel;

    ////////////////////////////////////////////////////////////////////////////////////////////////

    private PayStatusListener payStatusListener;

    public interface PayStatusListener {
        void onPay(int status, int code);
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////

    class JsImp {
        @JavascriptInterface
        public void callback_pay(final String tag, final String code) {
            mWebView.post(new Runnable() {
                public void run() {
                    if (payStatusListener != null && tag != null) {
                        try {
                            boolean retValue = Boolean.valueOf(tag);
                            payStatusListener.onPay(retValue ? PAY_STATUS_OK : PAY_STATUS_FAILED, 0);
                            payStatusListener = null;
                            dismiss();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }

        @JavascriptInterface
        public void showMsg(final String result) {
            WLog.d(tag, "showMsg: " + result);
        }

        /**
         * 返回主界面
         */
        @JavascriptInterface
        public void closePage() {
            mWebView.post(new Runnable() {
                @Override
                public void run() {
                    if (payStatusListener != null) {
                        payStatusListener.onPay(PAY_STATUS_FAILED, 0);
                        payStatusListener = null;
                    }
                    dismiss();
                }
            });
        }

        @JavascriptInterface
        public String getTVID() {
            return AuthSDK.getInstance().getValue(IAuthInterface.KEY_TVID);
        }

        @JavascriptInterface
        public String getSoftAppVer() {
            try {
                return String.valueOf(getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), 0).versionName);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            return null;
        }

        @JavascriptInterface
        public String getSDKVersion() {
            return String.valueOf(Build.VERSION.SDK_INT);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////

    public DialogPlanBuy(Context context, String pageUrl, String channel, PayStatusListener payStatusListener) {
        super(context);
        this.mWebView = new WasuCompFactory().createWasuWebView(context);
        this.pageUrl = pageUrl;
        this.channel = channel;
        this.payStatusListener = payStatusListener;
        init(context);
    }

    @SuppressLint("SetJavaScriptEnabled")
    protected void init(Context context) {
        if (mWebView == null) {
            return;
        }

        if (mWebView.getParent() != null) {
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
        }

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);

        setContentView(mWebView);

        Rect screenRect = SystemUtils.getScreenSize(getContext());
        getWindow().setLayout(screenRect.width(), screenRect.height());

        mWebView.addJavascriptInterface(new WR(getContext(), mWebView), "WR");
        mWebView.addJavascriptInterface(new WR_Term(getContext()), "WR_Term");
        mWebView.addJavascriptInterface(new WR_History(getContext()), "WR_History");
        mWebView.addJavascriptInterface(new WR_Favorites(getContext()), "WR_Favorites");
        mWebView.addJavascriptInterface(new tv(getContext()), "tv");
        mWebView.addJavascriptInterface(new WR_UserCenter(getContext()), "WR_UserCenter");

        if (payStatusListener != null) {
            mWebView.addJavascriptInterface(new JsImp(), "WR_Term");
        }

        if (!TextUtils.isEmpty(pageUrl)) {
            pageUrl = pageUrl + "&thirdChannel=" + (TextUtils.isEmpty(channel) ? "" : channel) + "&thirdIndentId=" + generateClientOrder();
        }

        setCancelable(true);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mWebView != null) {
            mWebView.loadUrl(TextUtils.isEmpty(pageUrl) ? "about:blank" : pageUrl);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mWebView != null) {
            mWebView.loadUrl("about:blank");
        }
    }

    protected String generateClientOrder() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINESE);
        String strDate = format.format(new Date());

        return AuthSDK.getInstance().getValue(IAuthInterface.KEY_MAC) + strDate + (int) (Math.random() * 1000);
    }

}
