package com.artisanic.helper.ad

import android.app.Activity
import android.util.Log
import com.tradplus.ads.base.bean.TPAdError
import com.tradplus.ads.base.bean.TPAdInfo
import com.tradplus.ads.open.interstitial.InterstitialAdListener
import com.tradplus.ads.open.interstitial.TPInterstitial

class AdInstLoad {
    private var mPlace: String
    private var adLoadListener: LoadListener? = null
    private var activity: Activity? = null

    constructor(activity: Activity, place: String, listener: LoadListener?) {
        this.mPlace = place
        this.adLoadListener = listener
        this.activity = activity
        init()
    }

    constructor(place: String, listener: LoadListener?) {
        this.mPlace = place
        this.adLoadListener = listener
        init()
    }

    private fun init() {
        val tpInterstitial = TPInterstitial(activity, mPlace)
        tpInterstitial.setAdListener(object : InterstitialAdListener {
            //广告加载完成 首个广告源加载成功时回调 一次加载流程只会回调一次
            override fun onAdLoaded(tpAdInfo: TPAdInfo?) {
                if (tpAdInfo != null) {
                    Log.d("ocean", "$mPlace 广告load成功，tpAdInfo有值")
                    InstAdCacheManager.Companion.instance.setAdCache(mPlace, tpInterstitial)
                    adLoadListener?.loaded(tpAdInfo)
                } else {
                    adLoadListener?.loadFailed("tpAdInfo没有值")
                    Log.d("ocean", "$mPlace tpAdInfo没有值")
                }
            }

            // 广告被点击
            override fun onAdClicked(tpAdInfo: TPAdInfo?) {
                Log.d("ocean", "$mPlace tradplus onAdClicked")
            }

            // 广告成功展示在页面上
            override fun onAdImpression(tpAdInfo: TPAdInfo?) {
                Log.d("ocean", "$mPlace tradplus onAdImpression")
            }

            // 广告加载失败
            override fun onAdFailed(error: TPAdError?) {
                adLoadListener?.loadFailed("code->${error?.errorCode}message->${error?.errorMsg}")
                Log.d("ocean", "$mPlace  load ad onError->code->${error?.errorCode}message->${error?.errorMsg}")
            }

            // 广告被关闭
            override fun onAdClosed(tpAdInfo: TPAdInfo?) {
                Log.d("ocean", "$mPlace tradplus onAdClosed")
            }

            // 视频播放开始（部分广告源支持）
            override fun onAdVideoStart(tpAdInfo: TPAdInfo?) {
                Log.d("ocean", "$mPlace tradplus onAdVideoStart")
            }

            //视频播放结束（部分广告源支持）
            override fun onAdVideoEnd(tpAdInfo: TPAdInfo?) {
                Log.d("ocean", "$mPlace tradplus onAdVideoEnd")
            }

            //视频播放失败（部分广告源支持）
            override fun onAdVideoError(tpAdInfo: TPAdInfo?, error: TPAdError?) {
                Log.d("ocean", "$mPlace onAdVideoError code->${error?.errorCode}message->${error?.errorMsg}")
            }
        })
        tpInterstitial.loadAd()
    }
}