package com.wasu.cs.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.text.Html;
import android.text.Spanned;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wasu.comp.ad.AdView;
import com.wasu.comp.ad.AdViewListener;
import com.wasu.comp.ad.WasuAdEngine;
import com.wasu.module.log.WLog;
import com.wasu.vast.model.AdExtension;

import cn.com.wasu.main.R;

import static cn.com.wasu.main.R.id.time;

/**
 * 边看边买dialog
 *
 * @author chenliang
 */

public class DialogBKBM extends Dialog {
    private String TAG = "DialogBKBM";

    private DialogBKBM mDialog;
    private Context mContext;
    private int mDuration = 15; // 展示时间（s） 传入默认15000
    private boolean mShowCountDown = true;
    private boolean mClickable = false;
    AdView adview; // 接收到的adview
    private int mRetry = 2; // 重试次数（共获取3次）
    private int mPos;

    //View
    private RelativeLayout mAdview; // 广告条
    private TextView mTime; // 计时器
    private ImageView mDetail; // 查看详情

    private void init(Context context) {
        mContext = context;
        setContentView(R.layout.dialog_bkbm);
        mDialog = this;
        initView();
        SetLocation();
        getADview();
    }

    private void initView() {
        mAdview = (RelativeLayout) findViewById(R.id.adview);
        mTime = (TextView) findViewById(time);
        mDetail = (ImageView) findViewById(R.id.ad_detail);
        mTime.setText(getDuration());

        if (!mClickable) {
            mDetail.setClickable(false);
        }
    }

    /**
     * 倒计时关闭定时器
     */
    private void setTimer() {
        final Handler handler = new Handler();
        final Runnable r = new Runnable() {
            @Override
            public void run() {
                if (mDuration > 0) {
                    mDuration = mDuration - 1;
                    mTime.setText(getDuration());
                    handler.postDelayed(this, 1000);
                } else {
                    handler.removeCallbacks(this);
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                    }
                }
            }
        };
        handler.postDelayed(r, 1000);
    }


    // 获得广告的view
    private void getADview() {
        WLog.e("WasuPlayerView", "getADview");
        if (mPos != 0) {
            adview = WasuAdEngine.getInstance().getImageAd(mPos/**url中的pos*/, 0/**没有取到图片默认的resId*/, false/**是否循环播放*/,
                    null/**map*/, /**listerner**/new AdViewListener() {
                        @Override
                        public void AdLoaded(AdView.Property property) {
//                    WLog.e("WasuPlayerView", "AdLoaded");
                            if (property.width() > 0 && property.height() > 0) {
                                setADSize(property.width(), property.height());
                            }
                            if (property.duration() > 0) {
                                mDuration = property.duration() / 1000;
                            }
                            mShowCountDown = property.showCountDown();
                            mClickable = property.clickable();
                        }

                        @Override
                        public void AdStarted(AdExtension adExtension) {
//                      WLog.e("WasuPlayerView", "AdStarted");
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && mContext != null && !((Activity) mContext).isDestroyed() && !((Activity) mContext).isFinishing()) {
                                mDialog.show();
                                setTimer();
                            } else if (mContext != null && !((Activity) mContext).isFinishing()) {
                                mDialog.show();
                                setTimer();
                            }
                        }

                        @Override
                        public void AdStopped() {
                            if (mRetry > 0) {
//                              WLog.e("WasuPlayerView", "AdStopped mRetry = "+mRetry+"  AdStopped, 尝试获取第"+bkbmIndex+"条");
                                mRetry = mRetry - 1;
                                getADview();
                            }
                        }

                        @Override
                        public void AdSkipped() {
                        }

                        @Override
                        public void AdError() {
                            if (mRetry > 0) {
//                              WLog.e("WasuPlayerView", "AdError mRetry = "+mRetry+"  AdStopped, 尝试获取第"+bkbmIndex +"条");
                                mRetry = mRetry - 1;
                                getADview();

                            }
                        }

                        @Override
                        public void AdClickThru(AdExtension adExtension) {

                        }

                        @Override
                        public void AdUserClose() {

                        }

                        @Override
                        public void AdPause() {

                        }

                        @Override
                        public void AdResume() {

                        }
                    });
            if (adview != null) {
                mAdview.removeAllViews();
                mAdview.addView(adview);
            }
        } else {
            WLog.e(TAG, "边看边买广告没有传入pos!");
        }
    }

    // 设置adview的大小
    private void setADSize(int width, int height) {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mAdview.getLayoutParams();
        params.width = width;
        params.height = height;
        mAdview.setLayoutParams(params);
    }

    /**
     * 计算出大小不同的时间
     */
    private Spanned getDuration() {
        String a = getContext().getResources().getString(R.string.duration);
        String b = String.format(a, mDuration + "");
        return Html.fromHtml(b);
    }

    // dialog位置
    private void SetLocation() {
        Window dialogWindow = mDialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
    }


    public DialogBKBM(Context context) {
        super(context);
        init(context);
    }

    public DialogBKBM(Context context, int themeResId, int pos) {
        super(context, themeResId);
        mPos = pos;
        init(context);
    }

    public DialogBKBM(Context context, int themeResId) {
        super(context, themeResId);
        init(context);
    }

    protected DialogBKBM(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        init(context);
    }
}
