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.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 com.thinkup.core.api.AdError;
import com.thinkup.core.api.TUAdInfo;
import com.thinkup.core.api.TUAdStatusInfo;
import com.thinkup.nativead.api.NativeAd;
import com.thinkup.nativead.api.TUNative;
import com.thinkup.nativead.api.TUNativeAdView;
import com.thinkup.nativead.api.TUNativeDislikeListener;
import com.thinkup.nativead.api.TUNativeEventExListener;
import com.thinkup.nativead.api.TUNativeNetworkListener;
import com.thinkup.nativead.api.TUNativePrepareExInfo;
import com.thinkup.nativead.api.TUNativePrepareInfo;
import com.thinkup.nativead.api.TUNativeView;

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 TUNative mATNative;
    private NativeAd mNativeAd;

    private void initNative(Context context, String nativeTopOnPlacementID) {
        if (mATNative == null) {
            //初始化广告加载对象
            mATNative = new TUNative(context, nativeTopOnPlacementID, new TUNativeNetworkListener() {
                @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;
        }
        TUAdStatusInfo 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<TUAdInfo> atAdInfoList = mATNative.checkValidAdCaches();
        ALog.i(TAG, "Valid Cahce size:" + (atAdInfoList != null ? atAdInfoList.size() : 0));
        if (atAdInfoList != null) {
            for (TUAdInfo adInfo : atAdInfoList) {
                ALog.i(TAG, "Cahce detail:" + adInfo.toString());
            }
        }

        return isReady;
    }

    public void showAd(TUNativeView 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 TUNativeEventExListener() {
                @Override
                public void onDeeplinkCallback(TUNativeAdView view, TUAdInfo adInfo, boolean isSuccess) {
                    ALog.i(TAG, "onDeeplinkCallback:" + adInfo.toString() + "--status:" + isSuccess);
                }

                @Override
                public void onAdImpressed(TUNativeAdView view, TUAdInfo 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(TUNativeAdView view, TUAdInfo 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(TUNativeAdView 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(TUNativeAdView 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(TUNativeAdView view, int progress) {
                    ALog.i(TAG, "native ad onAdVideoProgress:" + progress);
                }
            });

            mNativeAd.setDislikeCallbackListener(new TUNativeDislikeListener() {
                @Override
                public void onAdCloseButtonClick(TUNativeAdView view, TUAdInfo 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();

            TUNativePrepareInfo mNativePrepareInfo = null;

            try {
                mNativePrepareInfo = new TUNativePrepareExInfo();

                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;
    }
}
