package com.xm.test.myfilemaster.ad


import com.xm.test.myfilemaster.MyApplication
import com.xm.test.myfilemaster.ad.bean.PushCfg

object PushManager {


    /**
     * 新用户是否显示
     */
    fun newUserPush(newUserAvoidTime: Int): Boolean {
        val firstLaunchTime = MyApplication.fContext.queryDataStoreBlock(FIRST_LAUNCH_TIME_KEY, 0L)
        val flag = (System.currentTimeMillis() - firstLaunchTime) / 1000 > newUserAvoidTime
        return flag
    }

    /**
     * 所有推送是否推送大于间隔时间
     * @param interval 单位分钟
     */
    fun canPushNextTime(interval: Int): Boolean {
        val lastPushTime = MyApplication.fContext.queryDataStoreBlock(ALL_LAST_PUSH_TIME, 0)
        return (System.currentTimeMillis() - lastPushTime) / 1000 > interval
    }

    /**
     * 根据id判断通知是否可推送
     * @param actionId 功能或者场景的id
     */
    fun isPush(actionId: Int): Boolean {
        // 新用户是否显示
        val pushManagement = ComUtils.getPushConfig()
        if (!newUserPush(pushManagement.newuser_avoid_time)) {
            return false
        }

        // 渠道用户是否推送
        if (!UserChancelEx.getUserChancelSwitch(pushManagement.push_show)) {
            return false
        }

        //是否上次推送间隔大于配置间隔
        val isOganic = UserChancelEx.isOrganicUser()
        val interval = if (isOganic) pushManagement.o_push_interval else pushManagement.all_push_interval
        if (!canPushNextTime(interval)) {
            return false
        }

        //当前类型通知推送间隔是否大于配置间隔
        if (!actionTypeCanPsh(actionId)) {
            return false
        }
        return true
    }

    /**
     * 当前类型通知推送间隔是否大于配置间隔
     */
    private fun actionTypeCanPsh(actionId: Int): Boolean {
        val pushCfg: PushCfg? = ComUtils.getPushTypeData(actionId.toString())
        val pushInterval = pushCfg?.push_interval ?: 0
        val lastTypePushTime = MyApplication.fContext.queryDataStoreBlock(createByActionId(actionId), 0L)

        return (System.currentTimeMillis() - lastTypePushTime) / 1000 > pushInterval
    }

}