package kr.co.vividnext.sodalive.common

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.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK
import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import kr.co.vividnext.sodalive.R
import kr.co.vividnext.sodalive.live.LiveViewModel
import kr.co.vividnext.sodalive.live.room.LiveRoomActivity
import org.koin.android.ext.android.inject

class SodaLiveService : Service() {

    private val liveViewModel: LiveViewModel by inject()

    var roomId: Long = 0

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

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val content = intent?.getStringExtra("content") ?: "라이브 진행중"
        roomId = intent?.getLongExtra("roomId", 0) ?: 0L
        updateNotification(content)
        return START_STICKY
    }

    private fun updateNotification(content: String) {
        val notification = createNotification(content)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val foregroundServiceTypes = FOREGROUND_SERVICE_TYPE_MICROPHONE or
                FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK

            startForeground(
                Constants.LIVE_SERVICE_NOTIFICATION_ID,
                notification,
                foregroundServiceTypes
            )
        } else {
            startForeground(Constants.LIVE_SERVICE_NOTIFICATION_ID, notification)
        }
    }

    private fun createNotification(content: String): Notification {
        val notificationChannelId = "soda_live_service_foreground_service_channel"
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(
                    notificationChannelId,
                    getString(R.string.app_name),
                    NotificationManager.IMPORTANCE_DEFAULT
                )
            notificationManager.createNotificationChannel(channel)
        }

        val intent = Intent(this, LiveRoomActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
        val pendingIntent = PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_CANCEL_CURRENT
        )

        val notificationBuilder = NotificationCompat.Builder(this, notificationChannelId)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(getString(R.string.app_name))
            .setContentText(content)
            .setOngoing(true)
            .setSilent(true)
            .setContentIntent(pendingIntent)

        return notificationBuilder.build()
    }

    override fun onDestroy() {
        liveViewModel.quitRoom(roomId) { }
        super.onDestroy()
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        stopSelf()
    }

    companion object {
        fun stopService(context: Context) {
            val intent = Intent(context, SodaLiveService::class.java)
            context.stopService(intent)
        }
    }
}
