package com.base.appzxhy.business.service

import android.app.NotificationManager
import android.app.job.JobInfo
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.app.job.JobService
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.CountDownTimer
import androidx.work.Configuration
import com.base.appzxhy.BuildConfig
import com.base.appzxhy.bean.config.PopupConfigBean
import com.base.appzxhy.business.helper.EventUtils
import com.base.appzxhy.business.service.StayNotification.createPermanentNotification
import com.base.appzxhy.utils.LogEx


/**
 *  常驻通知栏
 */
class StayJobService : JobService() {

    init {
        val builder = Configuration.Builder()
        builder.setJobSchedulerJobIdRange(0, 1000)
    }


    companion object {
        private val TAG = "StayJobService"
        val NOTIFICATION_STAY_ID = 186


        private var isRunning = false
        private const val JOB_INFO_ID: Int = 101
        private var startJobTime = 0L
        private val minimumLatency = if (BuildConfig.DEBUG) 5000L else 5000L

        fun Context.startStayJobService() {
            if (isRunning) return
            LogEx.logDebug(TAG, "startJob")
            startJobTime = System.currentTimeMillis()
            val jobScheduler = getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler
            val componentName = ComponentName(this, StayJobService::class.java)
            val jobInfo = JobInfo.Builder(JOB_INFO_ID, componentName)
                .setMinimumLatency(minimumLatency)
                .build()
            jobScheduler.schedule(jobInfo)
        }

    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        LogEx.logDebug(TAG, "onStartCommand")
        return super.onStartCommand(intent, flags, startId)

    }

    private fun startForeground() {
        try {
            val notification = createPermanentNotification(applicationContext)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                startForeground(
                    NOTIFICATION_STAY_ID,
                    notification,
                    ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
                )
            } else {
                startForeground(NOTIFICATION_STAY_ID, notification)
            }
            isRunning = true
            EventUtils.event("startForeground")
            LogEx.logDebug(TAG, "startForeground")
        } catch (e: Exception) {
            EventUtils.event("start_foreground_service_error")
        }
    }

    private fun notifyForeground() {
//        LogEx.logDebug(TAG, "notifyForeground")
        val notificationManager =
            getSystemService(NOTIFICATION_SERVICE) as NotificationManager

        notificationManager.notify(NOTIFICATION_STAY_ID, createPermanentNotification(applicationContext))
    }

    override fun onDestroy() {
        isRunning = false
        super.onDestroy()
    }

    override fun onCreate() {
        LogEx.logDebug(TAG, "onCreate isRunning=$isRunning")
        if (!isRunning) {
            val startTime = System.currentTimeMillis() - startJobTime
            LogEx.logDebug(TAG, "onCreate startTime=$startTime")
            EventUtils.event("StayJobService_onCreate", "startTime=$startTime")
            isRunning = true
            startForeground()
            Timer().start()
        }
        super.onCreate()
    }

    override fun onStartJob(params: JobParameters?): Boolean {
        return true
    }

    override fun onStopJob(params: JobParameters?): Boolean {
        return false
    }

    val millisInFuture = if (BuildConfig.DEBUG) 5000L else PopupConfigBean.popupConfigBean.notifyForegroundInterval

    private inner class Timer() : CountDownTimer(millisInFuture, 1000) {
        override fun onTick(millisUntilFinished: Long) {
//            LogEx.logDebug(TAG, "Timer onTick")
        }

        override fun onFinish() {
//            LogEx.logDebug(TAG, "Timer onFinish")
            notifyForeground()
            Timer().start()
        }

    }


}

