package com.swiftcleaner.chovey.business.push

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
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 android.util.Log
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import androidx.work.Configuration
import com.swiftcleaner.chovey.GlobalConfig.ID_APP_INSTALL
import com.swiftcleaner.chovey.GlobalConfig.ID_APP_PROCESS
import com.swiftcleaner.chovey.GlobalConfig.ID_BATTERY_INFO
import com.swiftcleaner.chovey.GlobalConfig.ID_CLEAN_JUNK
import com.swiftcleaner.chovey.GlobalConfig.ID_LARGE_FILE_CLEANER
import com.swiftcleaner.chovey.GlobalConfig.KEY_NOTIFICATION_ID
import com.swiftcleaner.chovey.R
import com.swiftcleaner.chovey.business.admob.AdmobManager
import com.swiftcleaner.chovey.view.activity.AppProcessActivity
import com.swiftcleaner.chovey.view.activity.BatteryInfoActivity
import com.swiftcleaner.chovey.view.activity.CleanJunkActivity
import com.swiftcleaner.chovey.view.activity.InfoActivity
import com.swiftcleaner.chovey.view.activity.LargeFileActivity
import com.swiftcleaner.chovey.view.activity.StartActivity
import kotlin.random.Random

class NotificationJobService : JobService() {

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

    private val TAG = "NotificationJobService"
    private val ID = 56

    companion object {
        private var isRunning = false
        private const val JOB_ID = 101

        fun Context.startNotification() {
            if (isRunning) return
            val jobScheduler = getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler
            val componentName = ComponentName(this, NotificationJobService::class.java)
            val jobInfo = JobInfo.Builder(JOB_ID, componentName)
                .setMinimumLatency(1000)
                .build()
            jobScheduler.schedule(jobInfo)
        }
    }

    override fun onCreate() {
        if (!isRunning) {
            startForeground()
            isRunning = true
            Timer().start()
        }
        super.onCreate()
    }

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

    private fun startForeground() {
        val notification = createNotification(applicationContext)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(
                ID,
                notification,
                ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC
            )
        } else {
            startForeground(ID, notification)
        }
    }

    private fun notifyForeground() {
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        notificationManager.notify(ID, createNotification(applicationContext))
    }

    private fun createNotification(context: Context): Notification {
        val channelName = "Job Channel Name"
        val channelId = "Job Channel Id"
        val notificationLayout = RemoteViews(context.packageName, R.layout.notifi_stay_small)
        val notificationLayoutExpanded = RemoteViews(context.packageName, R.layout.notify_stay_big)
        val builder = NotificationCompat.Builder(context, channelId)
            .setSmallIcon(R.drawable.frame)
            .setContentTitle(context.resources.getString(R.string.app_name))
            .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
            .setAutoCancel(false)
            .setOngoing(true)
            .setNumber(0)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .setWhen(System.currentTimeMillis())
            .setCustomContentView(notificationLayout)
            .setCustomBigContentView(notificationLayoutExpanded)
            .setCategory(NotificationCompat.CATEGORY_CALL)

        val cleanPendingIntent = createPendingIntent(context, ID_CLEAN_JUNK, CleanJunkActivity::class.java)
        notificationLayout.setOnClickPendingIntent(R.id.id_ll_clean, cleanPendingIntent)
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.id_ll_clean, cleanPendingIntent)

        val largeFilePendingIntent = createPendingIntent(context, ID_LARGE_FILE_CLEANER, LargeFileActivity::class.java)
        notificationLayout.setOnClickPendingIntent(R.id.id_large_file, largeFilePendingIntent)
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.id_large_file, largeFilePendingIntent)

        val batteryPendingIntent = createPendingIntent(context, ID_BATTERY_INFO, InfoActivity::class.java)
        notificationLayout.setOnClickPendingIntent(R.id.id_battery, batteryPendingIntent)
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.id_battery, batteryPendingIntent)

        val appPendingIntent = createPendingIntent(context, ID_APP_PROCESS, AppProcessActivity::class.java)
        notificationLayout.setOnClickPendingIntent(R.id.id_app_manager, appPendingIntent)
        notificationLayoutExpanded.setOnClickPendingIntent(R.id.id_app_manager, appPendingIntent)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW)
            channel.lockscreenVisibility = NotificationCompat.VISIBILITY_PUBLIC
            channel.setShowBadge(false)
            val notificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
            builder.setChannelId(channelId)
        }
        return builder.build()
    }

    private fun createPendingIntent(context: Context, id: Int, clz: Class<*>): PendingIntent {
        val intent = Intent(context, clz)
        return PendingIntent.getActivity(context, Random.Default.nextInt(5000), intent, PendingIntent.FLAG_IMMUTABLE)
    }

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

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

    private inner class Timer : CountDownTimer(30000, 1000) {
        override fun onTick(millisUntilFinished: Long) {

        }

        override fun onFinish() {
            Log.e(TAG, "Timer:onFinish")
            notifyForeground()
            Timer().start()
        }
    }
}