package com.example.uitugasakhir.komponen

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.rememberNavController
import com.example.uitugasakhir.ManualScreen
import com.example.uitugasakhir.Page.NotifikasiScreen
import com.example.uitugasakhir.ViewModel.MainViewModel
import com.example.uitugasakhir.ViewModel.SensorViewModel
import viewmodel.NotificationViewModel
import okhttp3.*

class WebSocketClient(
    private val notifVm: NotificationViewModel
) {

    private val client = OkHttpClient()
    private var webSocket: WebSocket? = null

    fun connect() {

        val request = Request.Builder()
            .url("ws://server-kamu/ws") // ganti nanti
            .build()

        val listener = object : WebSocketListener() {

            override fun onMessage(webSocket: WebSocket, text: String) {
                notifVm.updateFromSocket(text)
            }

            override fun onFailure(
                webSocket: WebSocket,
                t: Throwable,
                response: Response?
            ) {
                t.printStackTrace()
            }
        }

        webSocket = client.newWebSocket(request, listener)
    }

    fun disconnect() {
        webSocket?.close(1000, "close")
    }
}




