package com.likewind.myapplication

import android.annotation.SuppressLint
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 android.widget.RemoteViews
import androidx.core.app.NotificationCompat
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import java.util.*

//const val channelId ="notification_channel"
//const val channelName = "com.eazyalgo.fcmpushnotification"




class MyFirebaseMessagingService : FirebaseMessagingService() {

    private val fileCreationHelper = FileCreationHelper()

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)

        //fileCreationHelper.createTextFile(this, "log.txt", "666666666666")
        //Handle the received message here
        //Log.d(TAG, "From: ${remoteMessage.from}")
        //fileCreationHelper.createTextFile(this, "log.txt", "From: ${remoteMessage.from}")

        // Retrieve the FCM token
        FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
            //Log.d(TAG, "FCM Token: $token")
            //fileCreationHelper.createTextFile(this, "log.txt", "FCM Token: $token")

            // Continue with the rest of the message handling...
            handleReceivedMessage(remoteMessage, token)
        }
    }

    private fun handleReceivedMessage(remoteMessage: RemoteMessage, token: String) {

        fileCreationHelper.createTextFile(this, "log.txt", "777777777777")
        // Check if the message contains data
        remoteMessage.data.isNotEmpty().let {
            //Log.d(TAG, "Message data payload: ${remoteMessage.data}")
            //fileCreationHelper.createTextFile(this, "log.txt", "Message data payload: ${remoteMessage.data}")

            // Get the URL from the data payload
            val url = remoteMessage.data["url"]
            val lang_ko = remoteMessage.data["lang_ko"]
            val lang_en = remoteMessage.data["lang_en"]
            val lang_es = remoteMessage.data["lang_es"]

            // Show the data in a Log message
            //Log.d(TAG, "Received URL: $url")
            //fileCreationHelper.createTextFile(this, "log.txt", "Received URL: $url")
            //fileCreationHelper.createTextFile(this, "log.txt", "Received lang_ko: $lang_ko")
            //fileCreationHelper.createTextFile(this, "log.txt", "Received lang_en: $lang_en")
            //fileCreationHelper.createTextFile(this, "log.txt", "Received lang_es: $lang_es")

            // Get title and body from data payload
            val title = remoteMessage.data["title"]
            val body = remoteMessage.data["body"]

            // Open the URL in the WebView if it's not null
            if (!url.isNullOrBlank()) {
                //fileCreationHelper.createTextFile(this, "log.txt", "88888888888888")
                broadcastUrlToMainActivity(url, lang_ko, lang_en, lang_es)
                // Display a notification
                showNotification(lang_ko, lang_en, lang_es, title, body, url)
            }

            //fileCreationHelper.createTextFile(this, "log.txt", "999999999999999")
        }
    }

    private fun showNotification(lang_ko: String?, lang_en: String?, lang_es: String?, title: String?, body: String?, url: String) {
        val (notificationTitle, notificationBody) = getNotificationContent(lang_ko, lang_en, lang_es, title, body)

        val channelId = "default_channel_id"
        val notificationId = generateNotificationId()

        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_stat_name)
            //.setContentTitle(notificationTitle ?: "Default Title")
            .setContentText(notificationBody ?: "Default Body")
            .setAutoCancel(true)
            .setContentIntent(createPendingIntent(url)) // Set the PendingIntent for when notification is clicked

        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "Default Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            notificationManager.createNotificationChannel(channel)
        }

        notificationManager.notify(notificationId, notificationBuilder.build())
    }

    private fun getNotificationContent(lang_ko: String?, lang_en: String?, lang_es: String?, title: String?, body: String?): Pair<String?, String?> {
        // Get the default locale of the device
        val defaultLocale = Locale.getDefault()
        val language = defaultLocale.language

        // Choose the appropriate language content for the notification
        val notificationTitle: String?
        val notificationBody: String?

        // Set notification content based on the device language
        when (language) {
            "ko" -> {
                notificationTitle = "한국어 타이틀"
                notificationBody = lang_ko
            }
            "en" -> {
                notificationTitle = "English Title"
                notificationBody = lang_en
            }
            "es" -> {
                notificationTitle = "Título en Español"
                notificationBody = lang_es
            }
            else -> {
                // Default to English if the device language is not supported
                notificationTitle = "English Title"
                notificationBody = lang_en
            }
        }

        return Pair(notificationTitle, notificationBody)
    }

    private fun createPendingIntent(url: String): PendingIntent {
        val intent = Intent(this, MainActivity::class.java)
        intent.action = ACTION_OPEN_URL
        intent.putExtra(EXTRA_URL, url)

        //fileCreationHelper.createTextFile(this, "log.txt", "bbbbbbbbbbbb")

        return PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_ONE_SHOT
        )
    }

    private fun broadcastUrlToMainActivity(url: String, lang_ko: String?, lang_en: String?, lang_es: String?) {
        val intent = Intent(ACTION_OPEN_URL)
        intent.putExtra(EXTRA_URL, url)
        intent.putExtra(EXTRA_LANG_KO, lang_ko)
        intent.putExtra(EXTRA_LANG_EN, lang_en)
        intent.putExtra(EXTRA_LANG_ES, lang_es)

        //fileCreationHelper.createTextFile(this, "log.txt", "cccccccccccc")
        sendBroadcast(intent)
    }

    private fun generateNotificationId(): Int {
        //fileCreationHelper.createTextFile(this, "log.txt", "dddddddddd")
        // Generate a unique notification ID using the current timestamp
        return System.currentTimeMillis().toInt()
    }

    companion object {
        private const val TAG = "MyFirebaseMsgService"
        const val ACTION_OPEN_URL = "action_open_url"
        const val EXTRA_URL = "extra_url"
        const val EXTRA_LANG_KO = "extra_lang_ko"
        const val EXTRA_LANG_EN = "extra_lang_en"
        const val EXTRA_LANG_ES = "extra_lang_es"
    }
}

/**
class MyFirebaseMessagingService : FirebaseMessagingService() {

    private val fileCreationHelper = FileCreationHelper()

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)


        fileCreationHelper.createTextFile(this, "log.txt", "666666666666")
        // Handle the received message here
        //Log.d(TAG, "From: ${remoteMessage.from}")
        fileCreationHelper.createTextFile(this, "log.txt", "From: ${remoteMessage.from}")

        // Retrieve the FCM token
        FirebaseMessaging.getInstance().token.addOnSuccessListener { token ->
            //Log.d(TAG, "FCM Token: $token")
            fileCreationHelper.createTextFile(this, "log.txt", "FCM Token: $token")

            // Continue with the rest of the message handling...
            handleReceivedMessage(remoteMessage, token)
        }
    }

    private fun handleReceivedMessage(remoteMessage: RemoteMessage, token: String) {

        fileCreationHelper.createTextFile(this, "log.txt", "777777777777")
        // Check if the message contains data
        remoteMessage.data.isNotEmpty().let {
            Log.d(TAG, "Message data payload: ${remoteMessage.data}")
            fileCreationHelper.createTextFile(this, "log.txt", "Message data payload: ${remoteMessage.data}")

            // Get the URL from the data payload
            val url = remoteMessage.data["url"]

            // Show the data in a Log message
            Log.d(TAG, "Received URL: $url")
            fileCreationHelper.createTextFile(this, "log.txt", "Received URL: $url")

            // Get title and body from data payload
            val title = remoteMessage.data["title"]
            val body = remoteMessage.data["body"]

            // Open the URL in the WebView if it's not null
            if (!url.isNullOrBlank()) {
                fileCreationHelper.createTextFile(this, "log.txt", "88888888888888")
                broadcastUrlToMainActivity(url)
                // Display a notification
                showNotification(title, body, url)
            }

            fileCreationHelper.createTextFile(this, "log.txt", "999999999999999")
        }
    }

    private fun showNotification(title: String?, body: String?, url: String) {
        val channelId = "default_channel_id"
        val notificationId = generateNotificationId()

        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_stat_name)
            .setContentTitle(title ?: "Default Title")
            .setContentText(body ?: "Default Body")
            .setAutoCancel(true)
            .setContentIntent(createPendingIntent(url))  // Set the PendingIntent for when notification is clicked

        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                channelId,
                "Default Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            notificationManager.createNotificationChannel(channel)
        }

        fileCreationHelper.createTextFile(this, "log.txt", "aaaaaaaaaaaaa")

        notificationManager.notify(notificationId, notificationBuilder.build())
    }

    private fun createPendingIntent(url: String): PendingIntent {
        val intent = Intent(this, MainActivity::class.java)

        intent.action = ACTION_OPEN_URL
        intent.putExtra(EXTRA_URL, url)

        fileCreationHelper.createTextFile(this, "log.txt", "bbbbbbbbbbbb")

        return PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_ONE_SHOT
        )
    }

    private fun broadcastUrlToMainActivity(url: String) {
        val intent = Intent(ACTION_OPEN_URL)
        intent.putExtra(EXTRA_URL, url)

        fileCreationHelper.createTextFile(this, "log.txt", "cccccccccccc")
        sendBroadcast(intent)
    }

    private fun generateNotificationId(): Int {
        fileCreationHelper.createTextFile(this, "log.txt", "dddddddddd")
        // Generate a unique notification ID using the current timestamp
        return System.currentTimeMillis().toInt()
    }

    companion object {
        private const val TAG = "MyFirebaseMsgService"
        const val ACTION_OPEN_URL = "action_open_url"
        const val EXTRA_URL = "extra_url"
    }
}
*/

