package ta1.cis.service

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.SharedPreferences
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.NotificationCompat
import com.pusher.client.Pusher
import com.pusher.client.PusherOptions
import com.pusher.client.connection.ConnectionEventListener
import com.pusher.client.connection.ConnectionState
import com.pusher.client.connection.ConnectionStateChange
import ta1.cis.R
import ta1.cis.activity.HomeActivity
import ta1.cis.helper.SharedPref

class NotificationService : Service() {

    private lateinit var pusher : Pusher;
    private lateinit var notificationManager: NotificationManager
    private lateinit var sharedPreferences: SharedPref

    override fun onCreate() {
        super.onCreate()
        pusher = setUpPusher()
        sharedPreferences = SharedPref(this)
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)
        val channel = pusher.subscribe("cis_channel")
        channel.bind("event-user-${sharedPreferences.getUserId()}") { event ->
            Log.d("Pusher1",event.data.toString())
            createNotification()
        }
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        TODO("Not yet implemented")
        return null
    }

    private fun createNotification() {
        // 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 = getString(R.string.channel_name)
            val descriptionText = getString(R.string.channel_description)
            val importance = NotificationManager.IMPORTANCE_DEFAULT
            val channel = NotificationChannel("tes", name, importance).apply {
                description = descriptionText
            }
            // Register the channel with the system
            notificationManager= getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(channel)
        }
        var builder = NotificationCompat.Builder(this, "tes")
            .setSmallIcon(R.drawable.logo_foreground  )
            .setContentTitle("Izin Bermalam")
            .setContentText("Izin bermalam sudah di setujui")
            .setStyle(NotificationCompat.BigTextStyle()
                .bigText("Izin bermalam sudah di setujui"))
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        val intent = Intent(this, HomeActivity::class.java)
        intent.putExtra("NotifType", "IB")
        val pendingIntent = PendingIntent
            .getActivity(this, 0, intent
                ,PendingIntent.FLAG_UPDATE_CURRENT)

        builder.setContentIntent(pendingIntent)
        builder.setAutoCancel(true)
        val mNotificationManager =
            this.getSystemService(NOTIFICATION_SERVICE) as NotificationManager


        mNotificationManager.notify(1,builder.build())
    }

    fun setUpPusher() : Pusher{
        val options = PusherOptions()
        options.setCluster("ap1");

        val pusher = Pusher("cf80100d02b84bc296bd", options)

        pusher.connect(object : ConnectionEventListener {
            override fun onConnectionStateChange(change: ConnectionStateChange) {
                Log.i("Pusher", "State changed from ${change.previousState} to ${change.currentState}")
            }

            override fun onError(
                message: String,
                code: String,
                e: Exception
            ) {
                Log.i("Pusher", "There was a problem connecting! code ($code), message ($message), exception($e)")
            }
        }, ConnectionState.ALL)
        return pusher;
    }
}