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.StatsStaticHelper;
import com.gem.media.splash.base.protocol.AdCallback;
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.TUNativePrepareInfo;
import com.thinkup.nativead.api.TUNativeView;

import java.util.List;

public class NativeAdClearManager {
    private static final String TAG = "NativeAdManager";
    private static NativeCleanAdStatusCallBack adStatusCallBack;
    public static final String P_1 = "1";
    public static final String P_2 = "2";
    public static final String P_3 = "3";

    private long requestTime = -1;


    private static String sAdId;

    private TUNative mATNative;
    private NativeAd mNativeAd;

    private AdCallback adCallback;
    private String adPosition;

    public void setAdCallback(AdCallback adCallback) {
        this.adCallback = adCallback;
    }


    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, nativeTopOnPlacementID, Constants.SCENARIO_NATIVE_CLEAR, adPosition);
                    }
                    if (null != adCallback) {
                        adCallback.onAdLoaded(Constants.NODE_REQUEST_SUCCESS_EID, 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, nativeTopOnPlacementID, Constants.SCENARIO_NATIVE_CLEAR);
                    }
                    if (null != adCallback) {
                        adCallback.onAdError(Constants.NODE_ERROR_EID, AdData.AD_TYPE_NATIVE, reason, requestTime);
                    }
                }
            });
        }
//        atNative.setAdSourceStatusListener(new ATAdSourceStatusListenerImpl());
    }

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

    public int loadAd() {
        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;
        }

        initNative(PictureApplication.getApplication(), sAdId);

        if (mATNative == null) {
            ALog.w(TAG, "   mATNative   ==  null" + "   " + PictureApplication.getApplication().getPackageName());
            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 (!NetworkUtils.isConnected(PictureApplication.getApplication())) {
//                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 = PictureApplication.getApplication().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, Constants.SCENARIO_NATIVE_CLEAR, adPosition);
            }
            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, Constants.SCENARIO_NATIVE_CLEAR, adPosition);
                    }
                    if (null != adCallback) {
                        adCallback.onAdShow(Constants.NODE_CLOSE_EID, AdData.AD_TYPE_NATIVE, "show", -1);
                        adCallback = null;
                    }
                }

                @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, Constants.SCENARIO_NATIVE_CLEAR, adPosition);
                    }

                    if (null != adCallback) {
                        adCallback.onAdClick(Constants.NODE_CLICK_EID, 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, Constants.SCENARIO_NATIVE_CLEAR);
                    }
                }

                @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, Constants.SCENARIO_NATIVE_CLEAR);
                    }
                }

                @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, Constants.SCENARIO_NATIVE_CLEAR, adPosition);
                    }
                    destroyAd();
                }
            });
            ALog.i(TAG, "showAd start" );
            mATNativeView.removeAllViews();

            TUNativePrepareInfo mNativePrepareInfo = null;

            try {
                mNativePrepareInfo = new TUNativePrepareInfo();

                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();
        }
        if (mATNative != null) {
            mATNative.setAdListener(null);
            mATNative.setAdSourceStatusListener(null);
        }
    }

    public static void setAdStatusCallBack(NativeCleanAdStatusCallBack adStatusCallBack) {
        if (null == NativeAdClearManager.adStatusCallBack) {
            NativeAdClearManager.adStatusCallBack = adStatusCallBack;
        }
    }

    public void setAdPosition(String adPosition) {
        this.adPosition = adPosition;
    }

    public String getAdPosition() {
        return adPosition;
    }
}
