package io.nexilis.service.core

import android.annotation.TargetApi
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.net.Uri
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.Person
import io.nexilis.service.R

class ChatNotification(private val context: Context) {

    @TargetApi(Build.VERSION_CODES.O)
    private fun createNotificationChannel(
        channelId: String,
        name: String
    ): NotificationChannel {
        return NotificationChannel(
            channelId, name, NotificationManager.IMPORTANCE_DEFAULT
        ).also { channel ->
            val notificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    fun getNotification(
        person: Person,
        title: String,
        text: String,
        time: Long,
        uri: Uri? = null
    ): Notification {
        val channelId = context.getString(R.string.notification_chat_channel_id)
        val name = context.getString(R.string.channel_name_chat)
        val style = with(NotificationCompat.MessagingStyle(person)) {
            uri?.let {
                addMessage(
                    NotificationCompat.MessagingStyle.Message("", time, person)
                        .setData("image/*", it)
                )
            }
            addMessage(NotificationCompat.MessagingStyle.Message(text, time, person))
        }
        val builder = NotificationCompat.Builder(context, channelId)
            .setContentTitle(title)
            .setContentText(text)
            .setSmallIcon(context.applicationInfo.icon)
            .setStyle(style)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel(channelId, name).also {
                builder.setChannelId(it.id)
            }
        }
        return builder.build()
    }

    fun getNotification(
        title: String,
        text: String,
        style: NotificationCompat.Style
    ): Notification {
        val channelId = context.getString(R.string.notification_chat_channel_id)
        val name = context.getString(R.string.channel_name_chat)
        val builder = NotificationCompat.Builder(context, channelId)
            .setContentTitle(title)
            .setContentText(text)
            .setSmallIcon(context.applicationInfo.icon)
            .setStyle(style)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel(channelId, name).also {
                builder.setChannelId(it.id)
            }
        }
        return builder.build()
    }

}