package com.epfl.esl.sportstracker

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import co.yml.charts.common.model.Point
import com.google.android.gms.tasks.Tasks
import com.google.android.gms.wearable.DataClient
import com.google.android.gms.wearable.DataEvent
import com.google.android.gms.wearable.DataEventBuffer
import com.google.android.gms.wearable.DataMapItem
import com.google.android.gms.wearable.MessageClient
import com.google.android.gms.wearable.Wearable

class ExerciseLiveViewModel: ViewModel(), DataClient.OnDataChangedListener {

    private val _heartRate = MutableLiveData<Int>(0)
    val heartRate: LiveData<Int>
        get() = _heartRate

    private val _heartRateList = ArrayList<Point>()
    private val _heartRateListLiveData = MutableLiveData<List<Point>>()
    val heartRateList: LiveData<List<Point>>
        get() = _heartRateListLiveData

    override fun onDataChanged(dataEvents: DataEventBuffer) {
        dataEvents
            .filter { it.type == DataEvent.TYPE_CHANGED
                    && it.dataItem.uri.path == "/heart_rate" }
            .forEach { event ->
                val newValue = DataMapItem.fromDataItem(event.dataItem)
                    .dataMap.getInt("HEART_RATE")
                _heartRate.value = newValue
                val x = _heartRateList.size
                val newPoint = Point(x.toFloat(), newValue.toFloat())
                _heartRateList.add(newPoint)
                _heartRateListLiveData.value = _heartRateList
            }
    }

    fun sendCommandToWear(command: String, context: Context) {
        Thread(Runnable {
            val connectedNodes: List<String> = Tasks
                .await(
                    Wearable
                        .getNodeClient(context).connectedNodes
                )
                .map { it.id }
            connectedNodes.forEach {
                val messageClient: MessageClient = Wearable
                    .getMessageClient(context)
                messageClient.sendMessage(it, "/command", command.toByteArray())
            }
        }).start()
    }
}