package com.maplehaze.adsdk.demo;

import android.app.Activity;
import android.content.Context;
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.MaplehazeSDK;
import com.maplehaze.adsdk.bean.AdEffect;
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.video.RewardVideoAd;

import static android.content.res.Configuration.ORIENTATION_LANDSCAPE;

public class RewardVideoActivity extends Activity implements View.OnClickListener {

    private final static String TAG = "RewardVideoActivity";

    private RewardVideoAd mVideoAd = null;

    private boolean mIsMute = false;
    private boolean isEnableServerConfig = 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_reward_video);
        ((EditText) findViewById(R.id.posId)).setText(Constants.REWARD_VIDEO_POS_ID);

        isEcpm = SharePfUtil.getEcpmConfig(this);
        isAdCallback = SharePfUtil.getAdCallBackToastConfig(this);
        biddingPrice = SharePfUtil.getBiddingPrice(this);
        isNoBiddingCompatibilityModel = SharePfUtil.getNoBiddingCompatibilityModeSwitch(this);






        this.findViewById(R.id.loadRewardVideoButton).setOnClickListener(this);
        this.findViewById(R.id.showRewardVideoButton).setOnClickListener(this);
//        RadioGroup radioGroup = findViewById(R.id.radioGroup);
//        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(RadioGroup group, int checkedId) {
//                switch (checkedId) {
//                    case R.id.portrait_rb:
//                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//                        ((EditText) findViewById(R.id.posId)).setText(Constants.REWARD_VIDEO_POS_ID);
//                        break;
//                    case R.id.landscape_rb:
//                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//                        ((EditText) findViewById(R.id.posId)).setText(Constants.REWARD_VIDEO_POS_ID);
//                        break;
//                    default:
//                        break;
//                }
//            }
//        });

        // option
        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;
            }
        });


        if (SharePfUtil.getDevelopMode(this)){
            isEnableServerConfig = true;
        }

        if (savedInstanceState!=null){
            RestartUtl.startClearLastTask(this);
        }
    }

    private RewardVideoAd.RewardVideoListener listener = new RewardVideoAd.RewardVideoListener() {


        /**
         * 请求成功
         */
        @Override
        public void onADCached() {
            Log.i(TAG, "onADCached");
            ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_load_ad_success);
        }

        /**
         * 曝光成功
         */
        @Override
        public void onADShow() {
            Log.i(TAG, "onAdShow");
            if (isAdCallback) {
                ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_ad_show);
            }

        }

        /**
         * 奖励
         */
        @Override
        public void onReward() {
            Log.i(TAG, "onReward");
            if (isAdCallback) {
                ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_ad_reward);
            }
        }

        /**
         * 广告点击
         */
        @Override
        public void onADClick() {
            Log.i(TAG, "onADClick");
            if (isAdCallback) {
                ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_ad_click);
            }
        }

        /**
         * 视频开始播放
         */
        @Override
        public void onVideoPlayStart() {
            Log.i(TAG, "onVideoPlayStart");
        }

        /**
         * 视频播放完成
         */
        @Override
        public void onVideoComplete() {
            Log.i(TAG, "onVideoComplete");
        }

        /**
         * 广告点击
         */
        @Override
        public void onADClose() {
            Log.i(TAG, "onADClose");
            if (isAdCallback) {
                ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_ad_close);
            }
        }

        /**
         * 广告出错
         */
        @Override
        public void onADError(int error) {
            Log.i(TAG, "onADError " + error);
            ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_ad_error, error));
        }
    };

    private void loadRewardVideoAd() {
        String posId = getPosID();

        int orientation = RewardVideoAd.VERTICAL;

        // 切换横屏
        int currentOrientation = getResources().getConfiguration().orientation;
        if (currentOrientation == ORIENTATION_LANDSCAPE) {
            orientation = RewardVideoAd.HORIZONTAL;
            posId = Constants.REWARD_VIDEO_POS_ID;
        }

        Context ctx = this;
        if (mVideoAd!=null){
            mVideoAd.onDestroy();
        }

        mVideoAd = new RewardVideoAd(ctx, posId, orientation, listener);
        mVideoAd.setMute(mIsMute);
        //---------------only for test -----------------------
        if (SharePfUtil.getDevelopMode(this)){
            mVideoAd.setTestEnableServerConfig(true);// only for demo
        }else{
            mVideoAd.setTestEnableServerConfig(isEnableServerConfig);// only for demo
        }
        //---------------only for test -----------------------
        mVideoAd.loadAd();
    }

    private void biddingAndShowAd() {

        if (mVideoAd != null && mVideoAd.isValid()) {
            if (isNoBiddingCompatibilityModel) {//兼容非竞价模式广告位
                int adEcpm = mVideoAd.getEcpm();
                if (adEcpm == -1) {//非竞价广告
                    Log.i(TAG, "非竞价广告 adEcpm=" + adEcpm);
                    if (isEcpm) {
                        ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_no_bidding_ecpm, adEcpm));
                    }
                    mVideoAd.showAd(this);
                } else if (biddingAd()) {//竞价模式
                    mVideoAd.showAd(this);
                } else {
                    ToastUtil.showToast(getApplicationContext(), R.string.mh_demo_no_ad_result);
                }
            } else {//竞价模式
                if (biddingAd()) {
                    mVideoAd.showAd(this);
                } 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 = mVideoAd.getEcpm();
        //竞价广告位需要和运营申请开通，非竞价模式返回的ecpm不作为有效价格
        int bidPrice = biddingPrice; //演示媒侧多预算价格过滤
        Log.i(TAG, "adEcpm=" + adEcpm + " bidPrice=" + bidPrice);
        boolean isWinBidding = false;
        if (adEcpm >= bidPrice) {
            //上报竞价成功，需要展示前上报
            int winPrice = adEcpm;//竞胜成交价
            mVideoAd.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;//竞胜方出价，接入的时候需要传入竞胜方出价
            mVideoAd.sendLossNotification(winPrice, MhBiddingLossReason.LOW_PRICE);
            if (isEcpm) {
                ToastUtil.showToast(getApplicationContext(), getString(R.string.mh_demo_bidding_fial, adEcpm));
            }
        }
        return isWinBidding;
    }

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

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.loadRewardVideoButton:
                OaidGetHelper.getInstance().initOaid(getApplicationContext());
                loadRewardVideoAd();
                break;
            case R.id.showRewardVideoButton:
                biddingAndShowAd();
                break;
            default:
                break;
        }
    }

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