package com.syaroful.agrilinkvocpro.control_feature.viewModel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.ValueEventListener
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

private const val TAG = "ControlViewModel"

class ControlViewModel : ViewModel() {

    private val _relayState = MutableStateFlow(false)
    val relayState: StateFlow<Boolean> = _relayState

    private val database = Firebase.database
    private val relayRef = database.getReference("relay1/state")

    init {
        observeRelayState()
    }

    private fun observeRelayState() {
        relayRef.get()
            .addOnSuccessListener { snapshot ->
                val value = snapshot.getValue(Int::class.java) ?: 0
                _relayState.value = (value == 1)
            }.addOnFailureListener{
                Log.e(TAG, "Failed to fetch initial relay state", it)
            }

        relayRef.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                val value = snapshot.getValue(Int::class.java) ?: 0
                _relayState.value = (value == 1)
            }
            override fun onCancelled(error: DatabaseError) {
                Log.e(TAG, "Failed to observe relay state", error.toException())
            }
        })
    }

    fun setRelayState(isOn: Boolean) {
        viewModelScope.launch {
            relayRef.setValue(if (isOn) 1 else 0)
                .addOnFailureListener {
                    Log.e(TAG, "Failed to set relay state", it)
                }
        }
    }
}