package com.maplehaze.adsdk.demo;

import android.app.Activity;
import android.os.Bundle;

import androidx.annotation.Nullable;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import com.maplehaze.adsdk.bid.MhBiddingLossReason;
import com.maplehaze.adsdk.demo.utils.OaidGetHelper;
import com.maplehaze.adsdk.demo.utils.RadioGroupUtil;
import com.maplehaze.adsdk.demo.utils.RestartUtl;
import com.maplehaze.adsdk.demo.utils.SharePfUtil;
import com.maplehaze.adsdk.demo.utils.ToastUtil;
import com.maplehaze.adsdk.interstitial.InterstitialAd;

public class InterstitialActivity extends Activity implements View.OnClickListener {
    private static final String TAG = "InterstitialActivity";
    private InterstitialAd interstitialAd;
    private String posId;


    private boolean isEnableServerConfig = false;


    private boolean mIsMute = false;
    private boolean isEcpm;
    private boolean isAdCallback;
    private int biddingPrice;
    private boolean isNoBiddingCompatibilityModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_interstitial);
        isEcpm = SharePfUtil.getEcpmConfig(this);
        isAdCallback = SharePfUtil.getAdCallBackToastConfig(this);
        biddingPrice = SharePfUtil.getBiddingPrice(this);
        isNoBiddingCompatibilityModel = SharePfUtil.getNoBiddingCompatibilityModeSwitch(this);
        ((EditText) findViewById(R.id.posId)).setText(Constants.INTERSTITIAL_POS_ID);
        findViewById(R.id.start_interstitial).setOnClickListener(this);
        findViewById(R.id.load_interstitial_btn).setOnClickListener(this);
        findViewById(R.id.show_interstitial_btn).setOnClickListener(this);



        CheckBox muteViewOptionCb = findViewById(R.id.muteOptionCb);
        muteViewOptionCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.i(TAG, "muteViewOptionCb check: " + isChecked);
                mIsMute = isChecked;
                updateTestConfig();
            }
        });



        if (SharePfUtil.getDevelopMode(this)){
            isEnableServerConfig = true;
        }
        if (savedInstanceState!=null){
            RestartUtl.startClearLastTask(this);
        }
    }

    private void loadInterstitialAd() {
        String posId = getPosID();
        if (interstitialAd != null && this.posId.equals(posId)) {
            return;
        }
        this.posId = posId;
        if (interstitialAd != null) {
            interstitialAd.close();
            interstitialAd.destroy();
            interstitialAd = null;
        }
        interstitialAd = new InterstitialAd(this, this.posId);
        updateTestConfig();
    }

    private void updateTestConfig() {
        if (interstitialAd != null) {
            interstitialAd.setMute(mIsMute);
            //---------------only for test -----------------------
            if (SharePfUtil.getDevelopMode(this)){
                interstitialAd.setTestEnableServerConfig(true);// only for test
            }else{
                interstitialAd.setTestEnableServerConfig(isEnableServerConfig);// only for test
            }
            //---------------only for test-----------------------
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_interstitial:
                loadAD(false);
                break;
            case R.id.load_interstitial_btn:
                loadAD(true);
                break;
            case R.id.show_interstitial_btn:
                biddingAndShowAd();
                break;
            default:
                break;

        }
    }

    private void loadAD(boolean isOnlyload) {
        OaidGetHelper.getInstance().initOaid(getApplicationContext());
        loadInterstitialAd();
        InterstitialAd.InterstitialAdListener listener = new InterstitialAd.InterstitialAdListener() {
            /**
             * 插屏加载成功
             */
            @Override
            public void onADReceive() {
                Log.d(TAG, "onADReceive 插屏加载成功");
                ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_load_ad_success);
                if (!isOnlyload) {
                    biddingAndShowAd();
                }
            }

            /**
             * 插屏曝光
             */
            @Override
            public void onADExposed() {
                Log.d(TAG, "onADExposed 插屏曝光");
                if (isAdCallback) {
                    ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_ad_show);
                }
            }

            /**
             * 插屏点击
             */
            @Override
            public void onADClicked() {
                Log.d(TAG, "onADClicked 插屏点击");
                if (isAdCallback) {
                    ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_ad_click);
                }
            }

            /**
             * 无广告
             */
            @Override
            public void onNoAD() {
                Log.d(TAG, "onNoAD");
                ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_no_ad_result);
            }

            /**
             * 异常
             */
            @Override
            public void onADError(int error) {
                Log.d(TAG, "onADError error=" + error);
                ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_ad_error, error));
            }

            @Override
            public void onAdClosed() {
                Log.d(TAG, "onAdClosed 插屏点击关闭");
                if (isAdCallback) {
                    ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_ad_close);
                }
            }
        };
        interstitialAd.setADListener(listener);
        interstitialAd.onlyLoadAd();
    }

    private void biddingAndShowAd() {
        if (interstitialAd != null && interstitialAd.isValid()) {
            if (isNoBiddingCompatibilityModel) {//兼容非竞价模式广告位
                int adEcpm = interstitialAd.getEcpm();
                if (adEcpm == -1) {//非竞价广告
                    Log.i(TAG, "非竞价广告 adEcpm=" + adEcpm);
                    interstitialAd.show();
                    if (isEcpm) {
                        ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_no_bidding_ecpm, adEcpm));
                    }
                } else if (biddingAd()) {//竞价模式
                    interstitialAd.show();
                } else {
                    ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_no_ad_result);
                }
            } else {//竞价模式
                if (biddingAd()) {
                    interstitialAd.show();
                } else {
                    if (!isEcpm) {
                        ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_no_bidding_ad);
                    }
                }
            }
        } else {
            ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_no_ad_result);
        }
    }


    private boolean biddingAd() {
        int adEcpm = interstitialAd.getEcpm();
        //竞价广告位需要和运营申请开通，非竞价模式返回的ecpm不作为有效价格
        int bidPrice = biddingPrice; //演示媒侧多预算价格过滤
        Log.i(TAG, "adEcpm=" + adEcpm + " bidPrice=" + bidPrice);
        boolean isWinBidding = false;
        if (adEcpm >= bidPrice) {
            //上报竞价成功，需要展示前上报
            int winPrice = adEcpm;//竞胜成交价
            interstitialAd.sendWinNotification(winPrice);
            isWinBidding = true;
            if (isEcpm) {
                ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_bidding_success, adEcpm));
            }
        } else {
            //MhBiddingLossReason.LOW_PRICE 竞争力不足
            //MhBiddingLossReason.NOT_COMPETITION 有广告回包但是未参与竞价
            //MhBiddingLossReason.NO_AD 无广告回包
            //MhBiddingLossReason.OTHER 其他（有回包）
            int winPrice = 1000;//竞胜方出价，接入的时候需要传入竞胜方出价
            interstitialAd.sendLossNotification(winPrice, MhBiddingLossReason.LOW_PRICE);
            if (isEcpm) {
                ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_bidding_fial, adEcpm));
            }
        }
        return isWinBidding;
    }


    private void closePopup() {
        if (interstitialAd != null) {
            interstitialAd.close();
        }
    }

    private String getPosID() {
        String posId = ((EditText) findViewById(R.id.posId)).getText().toString();
        return TextUtils.isEmpty(posId) ? Constants.INTERSTITIAL_POS_ID : posId;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (interstitialAd != null) {
            interstitialAd.destroy();
        }
        interstitialAd = null;
    }
}
