package com.ypsx.yppos.jobs

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import com.ypsx.base.base.appContext
import com.ypsx.yppos.R
import com.ypsx.yppos.http.repository.request.HttpRequestCoroutine
import com.ypsx.yppos.room.entity.PosConfig
import com.ypsx.yppos.room.repository.PosConfigRepository
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch


class LogService : Service() {
    var posConfig: PosConfig? = null
    var job: Job? = null

    companion object {

        var starter: Intent? = null

        fun start(context: Context) {
            if (starter == null){
                starter = Intent(context, LogService::class.java)
            }
            context.startService(starter)
        }

        fun stop(context: Context) {
            starter?.let {
                context.stopService(starter)
            }
        }
    }

    override fun onCreate() {
        super.onCreate()
        posConfig = PosConfigRepository.getInstance().loadConfig()
        job = GlobalScope.launch {
            HttpRequestCoroutine.uploadLog(posConfig?.code!!)
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        job?.cancel()
        stopForeground(true)
    }


    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        createEmptyNotification()
        return super.onStartCommand(intent, flags, startId)
    }

    private fun createEmptyNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            var channel = NotificationChannel(
                "CHANNEL_ID", "CHANNEL_NAME",
                NotificationManager.IMPORTANCE_HIGH
            )
            val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            manager.createNotificationChannel(channel)
            val notification =
                Notification.Builder(appContext, "CHANNEL_ID")
                    .setContentTitle("后台服务")
                    .setSmallIcon(R.drawable.icon_yp_logo)
                    .build()
            startForeground(1, notification)
//            startForeground(1, new Notification());
        }
    }
}