package com.birdsounds.identify


import android.content.Intent
import android.util.Half.abs
import android.util.Log
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.android.gms.wearable.MessageEvent
import com.google.android.gms.wearable.WearableListenerService
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.ShortBuffer

class MessageListenerService : WearableListenerService() {
    private val tag = "MessageListenerService"

    //    fun placeSoundClassifier(soundClassifier: SoundClassifier)
    override fun onMessageReceived(p0: MessageEvent) {
        super.onMessageReceived(p0)

//        MainActivity
        val soundclassifier = MainActivity.soundClassifier
        if (soundclassifier == null) {
            Log.w(tag, "Have invalid sound classifier")
            return
        } else {
            Log.w(tag, "Have valid classifier")
        }
        val short_array = ShortArray(48000 * 3)
        var tstamp_bytes = p0.data.copyOfRange(0, Long.SIZE_BYTES)
        var audio_bytes = p0.data.copyOfRange(Long.SIZE_BYTES, p0.data.size)
        var string_send: String = ""

        ByteBuffer.wrap(audio_bytes).order(
            ByteOrder.LITTLE_ENDIAN
        ).asShortBuffer().get(short_array)
        Log.w(tag, short_array.sum().toString())
        var sorted_list = soundclassifier.executeScoring(short_array)
        Log.w(tag, "")
        for (i in 0 until 5) {
            val score = sorted_list[i].value
            val index = sorted_list[i].index
            val species_name = soundclassifier.labelList[index]
            Log.w(tag, species_name + ", " + score.toString())
            string_send+= species_name
            string_send+=','
            string_send+=score.toString()
            string_send+=';'
        }
        MessageSenderFromPhone.sendMessage("/audio", tstamp_bytes + string_send.toByteArray(), this)
//        Log.i(tag , short_array.map( { abs(it)}).sum().toString())
//        Log.i(tag, short_array[0].toString())
//        Log.i(tag, p0.data.toString(Charsets.US_ASCII))
//        broadcastMessage(p0)
    }

}