package it.danieleverducci.openweddingapp.utils

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import it.danieleverducci.openweddingapp.Config
import it.danieleverducci.openweddingapp.MainActivity
import it.danieleverducci.openweddingapp.R
import org.json.JSONException
import org.json.JSONObject
import java.lang.RuntimeException
import java.util.*
import java.util.regex.Pattern

class NotificationUtils (val ctx: Context) {
    companion object {
        private val TAG = "NotificationUtils"
    }
    private val CHANNEL_ID = "123"
    private var notificationId = 0

    init {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = ctx.getString(R.string.channel_name)
            val descriptionText = ctx.getString(R.string.channel_description)
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
                description = descriptionText
            }
            // Register the channel with the system
            val notificationManager: NotificationManager =
                ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
    }

    fun createNotification(content: String) {
        val intent = Intent(ctx, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent: PendingIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_IMMUTABLE)

        /*
        Content is a JSON containing localization:
        {
          "it": {
            "title": "Lorem ipsum",
            "content": "Content content"
          },
          "es": {
            "title": "Lorem ipsum es",
            "content": "Content content es"
          }
        }
        */
        var contentJo: JSONObject? = null
        try {
            contentJo = JSONObject(content)
        } catch (e: JSONException) {
            Log.e(TAG, "Notification content is not a json!")
            return
        }

        val localized: JSONObject? =
            if (contentJo.has(Locale.getDefault().language)) contentJo.getJSONObject(Locale.getDefault().language)
            else contentJo.optJSONObject(Config.STATIC_CONTENT_DEFAULT_LOCALE)

        // Check language was found
        if (localized == null) {
            Log.e(TAG, "No supported language in received notification!")
            return
        }

        // Check required fields are present
        val title = localized.optString("title")
        val text = localized.optString("content")
        if (title.isEmpty()) {
            Log.e(TAG, "Missing title field in received notification!")
            return
        }
        if (text.isEmpty()) {
            Log.e(TAG, "Missing content field in received notification!")
            return
        }

        var builder = NotificationCompat.Builder(ctx, CHANNEL_ID)
            .setSmallIcon(R.drawable.ic_heart)
            .setContentTitle(title)
            .setContentText(text)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)

        with(NotificationManagerCompat.from(ctx)) {
            // notificationId is a unique int for each notification that you must define
            notify(notificationId, builder.build())
        }
        notificationId++

    }


}