package com.zxhyis.toolss.ad

import android.text.TextUtils
import com.blankj.utilcode.util.SPUtils
import com.zxhyis.toolss.FileApp
import com.zxhyis.toolss.ad.bean.AdsCfg
import org.json.JSONObject


object AdUtils {


    fun isShowAd(slot: String): Boolean {
        val adEntity = ComUtils.getAdPositionData(slot)
        if (!PushManager.newUserPush(adEntity.new_user_avoid_time)) {
            return false
        }
        if (!UserChancelEx.getUserChancelSwitch(adEntity.is_show)) {
            return false
        }
        if (TextUtils.equals(adEntity.type, "interstitial")) {
            AdmobUtils.adShowCount = adEntity.show_limit
            // AdmobUtils.adShowCount = 5

            // Log.e("MXL", "AdmobUtils.adShowCount: " + AdmobUtils.adShowCount)
            val isOrganic = UserChancelEx.isOrganicUser()
            if (isOrganic) {
                if (!canNextTime("interstitial", ComUtils.getComConfig().nature_insert_interval)) {
                    return false
                }
            } else {
                if (!canNextTime("interstitial", ComUtils.getComConfig().buy_insert_interval)) {
                    return false
                }
            }
        } else if (TextUtils.equals(adEntity.type, "native")) {
            AdmobUtils.nativeAdShowCount = adEntity.show_limit
            // AdmobUtils.nativeAdShowCount = 5
            //Log.e("MXL", "AdmobUtils.nativeAdShowCount: " + AdmobUtils.nativeAdShowCount)
        }
        if (!canNextTime(slot, adEntity.show_interval)) {
            return false
        }


//        val adNum = FileApp.fContext.queryDataStoreBlock(getIntString(slot + "_ad_show_num") , 0)
//        if (adNum >= adEntity.show_limit) {
//            return false
//        }

        return true

    }

    /**
     * 间隔
     * @param interval 单位分钟
     */
    private fun canNextTime(key: String, interval: Int): Boolean {
        val lastPushTime = FileApp.fContext.queryDataStoreBlock(getLongKey(key), 0)
        return (System.currentTimeMillis() - lastPushTime) / 1000 > interval
    }

    fun getLoadingTime() {
        val obj = JSONObject(ComUtils.getComConfigString())
        val adCig = obj.getJSONObject("ads_cfg")
        val adObj = adCig.getJSONObject("splash_slot")
        val entity: AdsCfg.AdEntity = AdsCfg.AdEntity()
        entity.loading_page_time = adObj.optInt("loading_page_time", 0)
        SPUtils.getInstance().put("loading_page_time", adObj.optInt("loading_page_time", 0))

    }

}