package com.gem.media.ad;

import static com.gem.media.ad.CpAdData.CP_TOPON;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;

import com.ads.cal.picturetranslate.PictureApplication;
import com.anythink.core.api.ATAdInfo;
import com.anythink.core.api.ATAdStatusInfo;
import com.anythink.core.api.AdError;
import com.anythink.nativead.api.ATNative;
import com.anythink.nativead.api.ATNativeAdView;
import com.anythink.nativead.api.ATNativeDislikeListener;
import com.anythink.nativead.api.ATNativeEventExListener;
import com.anythink.nativead.api.ATNativeNetworkListener;
import com.anythink.nativead.api.ATNativePrepareExInfo;
import com.anythink.nativead.api.ATNativePrepareInfo;
import com.anythink.nativead.api.ATNativeView;
import com.anythink.nativead.api.NativeAd;
import com.gem.media.NativeAdWindManager;
import com.gem.media.NetworkUtils;
import com.gem.media.StatsStaticHelper;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NativeAdManager {
    private static final String TAG = "NativeAdManager";
    private NativeAdStatusCallBack adStatusCallBack;

    private static final class NativeAdManagerHolder {
        static final NativeAdManager adManager = new NativeAdManager();
    }

    public static NativeAdManager getInstance() {
        return NativeAdManager.NativeAdManagerHolder.adManager;
    }
    private long requestTime = -1;

    private boolean canNNextRequestAd = true;

    private static String sAdId;

    private ATNative mATNative;
    private NativeAd mNativeAd;

    private void initNative(Context context, String nativeTopOnPlacementID) {
        if (mATNative == null) {
            //初始化广告加载对象
            mATNative = new ATNative(context, nativeTopOnPlacementID, new ATNativeNetworkListener() {
                @Override
                public void onNativeAdLoaded() {
                    ALog.i(TAG, "onNativeAdLoaded");
                    requestTime = System.currentTimeMillis() - requestTime;
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdLoaded(Constants.NODE_REQUEST_SUCCESS, AdData.AD_TYPE_NATIVE, "loaded", requestTime);
                    }
                    requestTime = System.currentTimeMillis();
                }

                @Override
                public void onNativeAdLoadFail(AdError adError) {
                    //注意：禁止在此回调中执行广告的加载方法进行重试，否则会引起很多无用请求且可能会导致应用卡顿
                    //AdError，请参考 https://newdocs.toponad.com/docs/55cxNt
                    ALog.i(TAG, "onNativeAdLoadFail:" + adError.getFullErrorInfo());
                    String reason = "interstitial " + "code: " + adError.getCode() + " msg: " + adError.getFullErrorInfo();
                    requestTime = System.currentTimeMillis() - requestTime;
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onNoAdError(Constants.NODE_ERROR, AdData.AD_TYPE_NATIVE, reason, requestTime);
                    }
                }
            });
        }
//        atNative.setAdSourceStatusListener(new ATAdSourceStatusListenerImpl());
    }

    public int loadAd(String sAdId, int i) {
        NativeAdManager.sAdId = sAdId;
        int status = loadAd(i);
        Map<String, String> map = new HashMap<>();
        map.put("status", String.valueOf(status));
        map.put("type", "native");
        StatsStaticHelper.onEvent(Constants.NODE_AD_REQ_STATUS, map);
        return status;
    }


    private volatile long lastAdRequestTime = 0;
    private static final long MIN_REQUEST_INTERVAL = 1000;

    private int loadAd(int i) {
        ALog.w(TAG, " mATNative  start load "+i);
        AdData adData = CpAdData.getInstance().getAdData(CP_TOPON);
        if (adData == null) {
            ALog.w(TAG, " mATNative  sAdId  get  adData == null");
        }
        if (TextUtils.isEmpty(sAdId) && null != adData) {
            sAdId = adData.getAdAdId(AdData.AD_TYPE_NATIVE);
        }
        if (TextUtils.isEmpty(sAdId)) {
            ALog.w(TAG, " mATNative  sAdId  is null ");
            return -1;
        }

        if (null != adData && !adData.canLoadAdData(AdData.AD_TYPE_NATIVE)) {
            ALog.w(TAG, " canLoadAdData  mATNative   ==  false");
            return -2;
        }

        initNative(PictureApplication.getApplication(), sAdId);

        if (mATNative == null) {
            ALog.w(TAG, "   mATNative   ==  null" + "   " );
            return -3;
        }
        ATAdStatusInfo atAdStatusInfo = mATNative.checkAdStatus();
        if (atAdStatusInfo.isReady()) {
            ALog.w(TAG, "mATNative is Ready");
        } else if (!atAdStatusInfo.isLoading()) {
            long currentTime = System.currentTimeMillis();
            if (Math.abs(currentTime - lastAdRequestTime) < MIN_REQUEST_INTERVAL) {
                return -8;
            }
            lastAdRequestTime = currentTime;
            if (!canNNextRequestAd) {
                return -4;
            }
//            if (!NetworkUtils.isConnected(A.getContext())) {
//                StatsStaticHelper.onEvent(Constants.NODE_AD_REQ_NOT_NET, "mATNative");
//                return -5;
//            }
            if (!CpAdData.adInitSuccess) {
                StatsStaticHelper.onEvent(Constants.NODE_AD_NOT_INIT, "mATNative");
                return -6;
            }

//            final int adViewWidth = A.getContext().getResources().getDisplayMetrics().widthPixels;
//            final int adViewHeight = adViewWidth * 3 / 4;
//            Map<String, Object> localExtra = new HashMap<>();
//            localExtra.put(ATAdConst.KEY.AD_WIDTH, adViewWidth);//单位：px，期望展示广告的宽度
//            localExtra.put(ATAdConst.KEY.AD_HEIGHT, adViewHeight);//单位：px，期望展示广告的高度

//            mATNative.setLocalExtra(localExtra);
            //发起广告请求

            if (null != adStatusCallBack) {
                adStatusCallBack.onAdLoad(Constants.NODE_REQUEST, AdData.AD_TYPE_NATIVE, "load", -1);
            }
            mATNative.makeAdRequest();
            ALog.w(TAG, "mATNative end load");
            return 1;
        } else {
            ALog.w(TAG, "mATNative is loading");
            return -7;
        }
        return 0;

    }

    public boolean isNativeAdReady() {
        if (mATNative == null) {
            return false;
        }
        boolean isReady = mATNative.checkAdStatus().isReady();
        ALog.i(TAG, "isAdReady: " + isReady);

        List<ATAdInfo> atAdInfoList = mATNative.checkValidAdCaches();
        ALog.i(TAG, "Valid Cahce size:" + (atAdInfoList != null ? atAdInfoList.size() : 0));
        if (atAdInfoList != null) {
            for (ATAdInfo adInfo : atAdInfoList) {
                ALog.i(TAG, "Cahce detail:" + adInfo.toString());
            }
        }

        return isReady;
    }

    public void showAd(ATNativeView mATNativeView, View mSelfRenderView) {
        if (!isNativeAdReady()) {
            return;
        }
        ALog.i(TAG, "showAd" );

//        NativeAd nativeAd = mATNative.getNativeAd();
        NativeAd nativeAd = mATNative.getNativeAd(AdConst.SCENARIO_ID.NATIVE_AD_SCENARIO);
        if (nativeAd != null) {
            if (mNativeAd != null) {
                mNativeAd.destory();
            }
            mNativeAd = nativeAd;

            mNativeAd.setNativeEventListener(new ATNativeEventExListener() {
                @Override
                public void onDeeplinkCallback(ATNativeAdView view, ATAdInfo adInfo, boolean isSuccess) {
                    ALog.i(TAG, "onDeeplinkCallback:" + adInfo.toString() + "--status:" + isSuccess);
                }

                @Override
                public void onAdImpressed(ATNativeAdView view, ATAdInfo entity) {
                    ALog.i(TAG, "native ad onAdImpressed:\n" + entity.toString());
                    requestTime = System.currentTimeMillis() - requestTime;
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdShow(Constants.NODE_SHOW, AdData.AD_TYPE_NATIVE, "show", requestTime);
                    }
                    loadAd(2);
                }

                @Override
                public void onAdClicked(ATNativeAdView view, ATAdInfo entity) {
                    ALog.i(TAG, "native ad onAdClicked:\n" + entity.toString());
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdClick(Constants.NODE_CLICK, AdData.AD_TYPE_NATIVE, "click", -1);
                    }
                }

                @Override
                public void onAdVideoStart(ATNativeAdView view) {
                    ALog.i(TAG, "native ad onAdVideoStart");
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onNativeAdVideoStart(Constants.NODE_NATIVE_AD_VIDEO_START, "native", "start video", -1);
                    }
                }

                @Override
                public void onAdVideoEnd(ATNativeAdView view) {
                    ALog.i(TAG, "native ad onAdVideoEnd");
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onNativeAdVideoEnd(Constants.NODE_NATIVE_AD_VIDEO_END, "native", "end video", -1);
                    }
                }

                @Override
                public void onAdVideoProgress(ATNativeAdView view, int progress) {
                    ALog.i(TAG, "native ad onAdVideoProgress:" + progress);
                }
            });

            mNativeAd.setDislikeCallbackListener(new ATNativeDislikeListener() {
                @Override
                public void onAdCloseButtonClick(ATNativeAdView view, ATAdInfo entity) {
                    ALog.i(TAG, "native ad onAdCloseButtonClick");
                    if (null != adStatusCallBack) {
                        adStatusCallBack.onAdDismiss(Constants.NODE_CLOSE, AdData.AD_TYPE_NATIVE, "close type: " + entity.getDismissType(), -1);
                    }
                    destroyAd();
                }
            });
            ALog.i(TAG, "showAd start" );
            mATNativeView.removeAllViews();

            ATNativePrepareInfo mNativePrepareInfo = null;

            try {
                mNativePrepareInfo = new ATNativePrepareExInfo();

                if (mNativeAd.isNativeExpress()) {
                    mNativeAd.renderAdContainer(mATNativeView, null);
                    ALog.i(TAG, "isNativeExpress" );
                } else {
                    SelfRenderViewUtil.bindSelfRenderView(PictureApplication.getApplication(), mNativeAd.getAdMaterial(), mSelfRenderView, mNativePrepareInfo);
                    mNativeAd.renderAdContainer(mATNativeView, mSelfRenderView);
                    ALog.i(TAG, "isSelfNativeExpress" );

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            ALog.i(TAG, "showAd end" );

            mNativeAd.prepare(mATNativeView, mNativePrepareInfo);
            mATNativeView.setVisibility(View.VISIBLE);
        } else {
            ALog.i(TAG, "this placement no cache!");
        }
    }

    public void destroyAd() {
        if (mNativeAd != null) {
            mNativeAd.destory();
        }
        NativeAdWindManager.getInstance().removeNativeAd();
        if (mATNative != null) {
            mATNative.setAdListener(null);
            mATNative.setAdSourceStatusListener(null);
        }
    }

    public void setAdStatusCallBack(NativeAdStatusCallBack adStatusCallBack) {
        this.adStatusCallBack = adStatusCallBack;
    }

    public void reload() {
        loadAd(3);
    }

    public void setCanNNextRequestAd(boolean canNNextRequestAd) {
        this.canNNextRequestAd = canNNextRequestAd;
    }
}
