package com.example.lexilearn.data.remote


import android.content.Context
import android.util.Log
import com.example.lexilearn.data.model.MaterialDataModel
import com.example.lexilearn.data.local.SharedPrefHelper
import com.google.firebase.database.*
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase

class FirebaseHelper(private val context: Context) {
    private val databaseReference: DatabaseReference =
        FirebaseDatabase.getInstance().getReference("data/animal")

    private val sharedPrefHelper = SharedPrefHelper(context)

    fun fetchMaterials(callback: (List<MaterialDataModel>) -> Unit) {
        databaseReference.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                val materialList = mutableListOf<MaterialDataModel>()
                for (materialSnapshot in snapshot.children) {
                    val material = materialSnapshot.getValue(MaterialDataModel::class.java)
                    material?.let { materialList.add(it) }
                }

                // Simpan ke SharedPreferences agar bisa diakses tanpa internet
                sharedPrefHelper.saveMaterialList(materialList)
                callback(materialList)
            }

            override fun onCancelled(error: DatabaseError) {
                Log.e("FirebaseHelper", "Error: ${error.message}")
            }
        })
    }
}
