package  com.base.filerecoveryrecyclebin.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.graphics.BitmapFactory
import android.graphics.drawable.Icon
import android.os.Build
import android.os.Environment
import android.os.IBinder
import android.provider.MediaStore
import android.widget.RemoteViews
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.graphics.drawable.IconCompat
import com.base.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.activity.MainActivity
import com.base.filerecoveryrecyclebin.activity.recyclebin.MediaContentObserver
import com.base.filerecoveryrecyclebin.activity.recyclebin.MyFileObserver
import com.base.filerecoveryrecyclebin.activity.splash.Splash2Activity
import com.base.filerecoveryrecyclebin.bean.ConstObject
import com.base.filerecoveryrecyclebin.bean.ConstObject.SCAN_DOCUMENTS
import com.base.filerecoveryrecyclebin.bean.ConstObject.SCAN_PHOTOS
import com.base.filerecoveryrecyclebin.bean.ConstObject.SCAN_VIDEOS
import com.base.filerecoveryrecyclebin.help.FileHelp
import com.base.filerecoveryrecyclebin.utils.EventUtils
import com.base.filerecoveryrecyclebin.utils.LogEx
import java.io.File
import kotlin.random.Random


/**
 *  常驻通知栏
 */
class StayNotificationService : Service() {

    private val TAG = "StayNotificationService"
    private var fileObserver: FileObserverExample? = null

    companion object {
        const val MEDIA_OBSERVER_ACTION = "media_observer_action"
        const val FILE_OBSERVER_ACTION = "file_observer_action"

        var isRunning = false

        fun Context.startStayNotification() {
            val intent = Intent(this, StayNotificationService::class.java)
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU) {
                //Android 14 no
                return
            }
            runCatching {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(intent)
                } else {
                    startService(intent)
                }
            }
        }
    }


    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent == null) {
            EventUtils.event("onStartCommand", "Foreground System auto launch intent=null isRunning=$isRunning")
            return START_NOT_STICKY
        }
        if (fileObserver == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                fileObserver = FileObserverExample()
                fileObserver?.startObserving()
            }
        }
        if (!isRunning) {
            runCatching {
                val notification = createPermanentNotification(applicationContext)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
                } else {
                    startForeground(1, notification)
                }
            }
            isRunning = true
        }

        return START_NOT_STICKY
    }

    private var mediaContentObserver: MediaContentObserver? = null

    private fun observerMediaContentObserver() {
        if (mediaContentObserver == null) {
            LogEx.logDebug(TAG, "observerMediaContentObserver")
            mediaContentObserver = MediaContentObserver(this)
            mediaContentObserver?.let {
                this.contentResolver.registerContentObserver(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true, it
                )
                this.contentResolver.registerContentObserver(
                    MediaStore.Video.Media.EXTERNAL_CONTENT_URI, true, it
                )

            }

        }
    }


    private var myFileObserver: MyFileObserver? = null

    @RequiresApi(Build.VERSION_CODES.Q)
    fun startMyFileObserver() {
        if (myFileObserver == null) {
            LogEx.logDebug(TAG, "startMyFileObserver")
            val dcimList =
                FileHelp.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM))
            val pictureList =
                FileHelp.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES))
            val downloadList =
                FileHelp.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS))
            val videoList =
                FileHelp.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES))

            val watchList = arrayListOf<File>()
            watchList.addAll(dcimList)
            watchList.addAll(pictureList)
            watchList.addAll(downloadList)
            watchList.addAll(videoList)
            watchList.forEach {
                LogEx.logDebug(TAG, "watchList=${it.absolutePath}")
            }
            myFileObserver = MyFileObserver(watchList)
            LogEx.logDebug(TAG, "watchList=${dcimList.size}")
            myFileObserver?.startWatching()
        }
    }


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

    override fun onDestroy() {
        isRunning = false
        super.onDestroy()
        // 取消监听

        fileObserver?.stopObserving()
    }

    private fun createPermanentNotification(context: Context): Notification {

        val isOngoing = true //是否持续(为不消失的常驻通知)
        val channelName = "File Recovery Foreground Service Channel"
        val channelId = "File_Recovery_Service_Id"
        val category = Notification.CATEGORY_SERVICE
        val contentView = RemoteViews(context.packageName, R.layout.stay_notification_big)
        val expendView = RemoteViews(context.packageName, R.layout.stay_notification_big)

        val requestCode1 = Random.nextInt(1800)
        val intent0 = Intent(context, Splash2Activity::class.java).apply {
            putExtra("actionId", ConstObject.ID_JUNK_CLEAN_PUSH)
        }
        val pendingIntent0 =
            PendingIntent.getActivity(context, requestCode1, intent0, PendingIntent.FLAG_IMMUTABLE)
        contentView.setOnClickPendingIntent(R.id.id_ll_clean, pendingIntent0)
        expendView.setOnClickPendingIntent(R.id.id_ll_clean, pendingIntent0)

        val requestCode2 = Random.nextInt(1800)
        val intent2 = Intent(context, Splash2Activity::class.java).apply {
            putExtra("actionId", ConstObject.ID_RECOVERY_PHOTOS)
            putExtra("ScanType", SCAN_PHOTOS)
        }
        val pendingIntent2 =
            PendingIntent.getActivity(context, requestCode2, intent2, PendingIntent.FLAG_IMMUTABLE)
        contentView.setOnClickPendingIntent(R.id.id_recovery_photos, pendingIntent2)
        expendView.setOnClickPendingIntent(R.id.id_recovery_photos, pendingIntent2)

        val requestCode3 = Random.nextInt(1800)
        val intent3 = Intent(context, Splash2Activity::class.java).apply {
            putExtra("actionId", ConstObject.ID_RECOVERY_VIDEOS)
            putExtra("ScanType", SCAN_VIDEOS)
        }
        val pendingIntent3 =
            PendingIntent.getActivity(context, requestCode3, intent3, PendingIntent.FLAG_IMMUTABLE)
        contentView.setOnClickPendingIntent(R.id.id_recovery_videos, pendingIntent3)
        expendView.setOnClickPendingIntent(R.id.id_recovery_videos, pendingIntent3)

//        val intent4 = Intent()
//        val serviceComponent = ComponentName(context, FlashlightService::class.java)
//        intent4.component = serviceComponent
//        val pendingIntent4 =
//            PendingIntent.getService(context, 0, intent4, PendingIntent.FLAG_IMMUTABLE)
//        contentView.setOnClickPendingIntent(R.id.id_screenshot, pendingIntent4)
//        expendView.setOnClickPendingIntent(R.id.id_screenshot, pendingIntent4)

        val requestCode4 = Random.nextInt(1800)
        val intent4 = Intent(context, Splash2Activity::class.java).apply {
            putExtra("actionId", ConstObject.ID_RECOVERY_DOCUMENTS)
            putExtra("ScanType", SCAN_DOCUMENTS)
        }
        val pendingIntent4 =
            PendingIntent.getActivity(context, requestCode4, intent4, PendingIntent.FLAG_IMMUTABLE)
        contentView.setOnClickPendingIntent(R.id.id_recovery_documents, pendingIntent4)
        expendView.setOnClickPendingIntent(R.id.id_recovery_documents, pendingIntent4)

        val nfIntent = Intent(context, MainActivity::class.java)
        val pendingIntent =
            PendingIntent.getActivity(context, 0, nfIntent, PendingIntent.FLAG_IMMUTABLE)

        val builder = NotificationCompat.Builder(context, channelId)

        val smallIcon = IconCompat.createFromIcon(
            context, Icon.createWithResource(
                this, R.drawable.icon_100
            )
        )
        smallIcon?.let {
            builder.setSmallIcon(smallIcon) //设置状态栏内的小图标
        }
        builder.setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.logo))
        builder.setContentTitle(context.resources.getString(R.string.app_name))
        builder.setContentIntent(pendingIntent) //设置PendingIntent
        builder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE) //设置通知公开可见
        builder.setAutoCancel(false)
        builder.setPriority(NotificationCompat.PRIORITY_MAX) //优先级为：重要通知
        builder.setWhen(System.currentTimeMillis())
        builder.setCustomContentView(contentView)
        builder.setCustomBigContentView(expendView)

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