package com.gem.media.ad;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.anythink.core.api.ATAdConst;
import com.anythink.core.api.ATBiddingListener;
import com.anythink.core.api.ATBiddingNotice;
import com.anythink.core.api.ATBiddingResult;
import com.anythink.rewardvideo.unitgroup.api.CustomRewardVideoAdapter;

import org.coolgam.OneH5Sdk;
import org.coolgam.om.OmAdError;
import org.coolgam.om.OmRewardAd;
import org.coolgam.om.OmSdk;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

public class OneH5RewardVideoAdapter extends CustomRewardVideoAdapter {
    private final AtomicBoolean isInit = new AtomicBoolean(false);
    private OmRewardAd omRewardAd;
    private String unit_id;

    @Override
    public void show(Activity activity) {
        postOnMainThread(new Runnable() {
            @Override
            public void run() {
                _show(activity);
            }
        });
    }

    private void _show(Activity activity) {
        if (omRewardAd == null || !omRewardAd.isAdReady()) {
            if (mImpressionListener != null) {
                mImpressionListener.onRewardedVideoAdPlayFailed("3", "RewardAd is not ready");
            }
            return;
        }
        omRewardAd.showAd(activity);
    }

    @Override
    public void loadCustomNetworkAd(Context context, Map<String, Object> map, Map<String, Object> map1) {
        loadCustomNetworkAd(context, map, map1, false, null);
    }

    public void loadCustomNetworkAd(Context context, Map<String, Object> map, Map<String, Object> map1, boolean isBidding, ATBiddingListener biddingListener) {
        if (map != null && map.containsKey("unit_id")) {
            unit_id = (String) map.get("unit_id");
        }
        if (isInit.get() || !TextUtils.isEmpty(OneH5Sdk.getAppId())) {
            postOnMainThread(new Runnable() {
                @Override
                public void run() {
                    loadAd(context, isBidding, biddingListener);
                }
            });
            return;
        }
        if (map == null || !map.containsKey("app_id")) {
            if (isBidding) {
                onBiddingFail(biddingListener, "topon config app_id is empty");
            } else {
                if (mLoadListener != null)
                    mLoadListener.onAdLoadError("400", "topon config app_id is empty");
            }
            return;
        }
        isInit.set(true);
        postOnMainThread(new Runnable() {
            @Override
            public void run() {
                initSdk(context, (String) map.get("app_id"), isBidding, biddingListener);
            }
        });
    }

    private void initSdk(Context context, String appId, boolean isBidding, ATBiddingListener biddingListener) {
        OmSdk.initialize((Application) context.getApplicationContext(), appId, new OmSdk.OnInitListener() {
            @Override
            public void onInitComplete(boolean isSuccess, String s) {
                if (isSuccess) {
                    loadAd(context, isBidding, biddingListener);
                } else {
                    Log.e("OneH5Sdk>>>", "init fail>>>" + s);
                    if (isBidding) {
                        onBiddingFail(biddingListener, s);
                    } else {
                        if (mLoadListener != null) {
                            mLoadListener.onAdLoadError("400", s);
                        }
                    }
                }
            }
        });
    }

    private void loadAd(Context context, boolean isBidding, ATBiddingListener biddingListener) {
        if (omRewardAd == null) {
            omRewardAd = new OmRewardAd();
            omRewardAd.setAdListener(new OmRewardAd.OnRewardAdListener() {
                @Override
                public void onAdLoaded() {
                    if (isBidding) {
                        onBiddingSuccess(biddingListener);
                        return;
                    }
                    if (mLoadListener != null)
                        mLoadListener.onAdCacheLoaded();
                }

                @Override
                public void onAdLoadFail(OmAdError omAdError) {
                    if (isBidding) {
                        onBiddingFail(biddingListener, omAdError.toString());
                        return;
                    }
                    if (mLoadListener != null)
                        mLoadListener.onAdLoadError(omAdError.code, omAdError.msg);
                }

                @Override
                public void onAdDismissed() {
                    if (mImpressionListener != null) {
                        mImpressionListener.onRewardedVideoAdClosed();
                    }
                }

                @Override
                public void onAdShowFail(OmAdError omAdError) {
                    if (mImpressionListener != null) {
                        mImpressionListener.onRewardedVideoAdPlayFailed(omAdError.code, omAdError.msg);
                    }
                }

                @Override
                public void onAdShowed() {
                    if (mImpressionListener != null) {
                        mImpressionListener.onRewardedVideoAdPlayStart();
                    }
                }

                @Override
                public void onAdReward() {
                    if (mImpressionListener != null) {
                        mImpressionListener.onReward();
                    }
                }
            });
        }
        omRewardAd.loadAd(context);
    }

    @Override
    public void destory() {
        if (omRewardAd != null) {
            omRewardAd.destory();
            omRewardAd = null;
        }
    }

    @Override
    public String getNetworkPlacementId() {
        return unit_id;
    }

    @Override
    public String getNetworkSDKVersion() {
        return OneH5Sdk.getSdkVersion();
    }

    @Override
    public String getNetworkName() {
        return OneH5Sdk.getSdkName();
    }

    @Override
    public boolean isAdReady() {
        return omRewardAd != null && omRewardAd.isAdReady();
    }

    @Override
    public boolean startBiddingRequest(Context context, Map<String, Object> serverExtra, Map<String, Object> localExtra, ATBiddingListener biddingListener) {
        loadCustomNetworkAd(context, serverExtra, localExtra, true, biddingListener);
        return true;
    }

    private void onBiddingFail(ATBiddingListener biddingListener, String msg) {
        //通过ATBiddingListener，回调竞价失败
        if (biddingListener != null) {
            biddingListener.onC2SBiddingResultWithCache(ATBiddingResult.fail(msg), null);
        }
    }

    private void onBiddingSuccess(ATBiddingListener biddingListener) {
        if (biddingListener == null || !isAdReady()) return;
        //获取价格
        double bidPrice = omRewardAd.getPrice();
        //获取货币单位
        ATAdConst.CURRENCY currency = ATAdConst.CURRENCY.USD;
        //用于标识此次竞价的唯一ID，可使用UUID或者时间戳
        String token = UUID.randomUUID().toString();
        //通知TopOn SDK竞价结果

        //注意：onC2SBiddingResultWithCache(ATBiddingResult biddingResult, BaseAd baseAd)原生广告需要返回BaseAd，其他广告形式可传null
        biddingListener.onC2SBiddingResultWithCache(ATBiddingResult.success(bidPrice, token, new ATBiddingNotice() {
            @Override
            public void notifyBidWin(double costPrice, double secondPrice, Map<String, Object> extra) {
                //costPrice：竞胜方价格
                //secondPrice：竞胜方后一位的价格（二价）
                if (omRewardAd != null) {
                    omRewardAd.notifyBid("TopOn", true, bidPrice, costPrice, secondPrice, "");
                }
            }

            @Override
            public void notifyBidLoss(String lossCode, double winPrice, Map<String, Object> extra) {
                //判断竞败原因
                String lossReason = "";
                switch (lossCode) {
                    case ATAdConst.BIDDING_TYPE.BIDDING_LOSS_WITH_BIDDING_TIMEOUT://竞价超时，如因长时间无竞价结果通知TopOn SDK
                        lossReason = "竞价超时，如因长时间无竞价结果通知TopOn SDK";
                        break;
                    case ATAdConst.BIDDING_TYPE.BIDDING_LOSS_WITH_LOW_PRICE_IN_HB://比竞价广告的价格低
                    case ATAdConst.BIDDING_TYPE.BIDDING_LOSS_WITH_LOW_PRICE_IN_NORMAL://比普通常规广告的价格低
                        lossReason = "比竞价广告的价格低";
                        break;
                    case ATAdConst.BIDDING_TYPE.BIDDING_LOSS_WITH_EXPIRE://广告缓存过期
                        lossReason = "广告缓存过期";
                        break;
                }
                //判断竞胜方渠道
//                int adnId = ATInitMediation.getIntFromMap(extra, ATBiddingNotice.ADN_ID, -1);
//                String lossAdn = "";
//                switch (adnId) {
//                    case ATAdConst.BIDDING_ADN_ID.LOSE_TO_NORMAL_IN_SAME_ADN://输给了同个广告平台的普通常规广告
//                        lossAdn = "输给了同个广告平台的普通常规广告";
//                        break;
//                    case ATAdConst.BIDDING_ADN_ID.LOSE_TO_HB_IN_SAME_ADN://输给了同个广告平台的竞价广告
//                        lossAdn = "输给了同个广告平台的竞价广告";
//                        break;
//                    case ATAdConst.BIDDING_ADN_ID.LOSE_TO_OWN_ADN://输给了自有广告（直投广告、交叉推广）
//                        lossAdn = "输给了自有广告（直投广告、交叉推广）";
//                        break;
//                    case ATAdConst.BIDDING_ADN_ID.LOSE_TO_OTHER_ADN://输给了其他广告平台
//                        lossAdn = "输给了其他广告平台";
//                        break;
//                }
                if (omRewardAd != null) {
                    omRewardAd.notifyBid("TopOn", false, bidPrice, winPrice, 0, lossReason);
                }
            }

            @Override
            public void notifyBidDisplay(boolean isWinner, double displayPrice) {
//                Log.e("oneh5", ">>notifyBidDisplay>>" + isWinner + ">>" + displayPrice);
            }

            @Override
            public ATAdConst.CURRENCY getNoticePriceCurrency() {
                return ATAdConst.CURRENCY.USD;
            }
        }, currency), null);
    }
}
