package com.birdsounds.identify.presentation

import android.content.Context
import android.util.Log
import androidx.compose.ui.platform.LocalContext
import com.google.android.gms.wearable.MessageEvent
import com.google.android.gms.wearable.WearableListenerService
import kotlinx.coroutines.delay
import java.nio.ByteBuffer

var last_message_recv_tstamp: Long = 0L;

class MessageListenerService : WearableListenerService() {
    private val tag = "MessageListenerService"
    lateinit var  this_context: Context;
    fun set_context(context: Context)
    {
        this_context = context;
    }

    override fun onMessageReceived(p0: MessageEvent) {
        super.onMessageReceived(p0)
        val t_scored = ByteBuffer.wrap(p0.data).getLong()
        last_message_recv_tstamp = t_scored;

        var byte_strings: ByteArray = p0.data.copyOfRange(8, p0.data.size)
        var score_species_string = byte_strings.decodeToString()
        var list_strings: List<String> = score_species_string.split(';')
        var do_vibrate = false;
        var did_add = false;
        var new_entries = 0;
//        bird_heard_state = BirdHeardState.NotHearing
        SpeciesList.bird_not_heard();
        list_strings.map({
            var split_str = it.split(',')
            if ((split_str.size == 2)  && !(split_str[0]=="bird1_bird1")) {
                Log.d(TAG, split_str[0] + "${split_str[0] == "bird1"}")
                new_entries+=1;
                var out = AScore(split_str[0], split_str[1].toFloat(), t_scored, true);
                out.new_entry = true;

                if (SpeciesList.add_observation(out))
                {
                    did_add = true;
                }
                do_vibrate = true;
            }
            else if (split_str[0]=="bird1_bird1") {
             Log.d(TAG, "I AM HEARING A BIRD")
                SpeciesList.bird_heard();
//                bird_heard_state = BirdHeardState.Hearing

            }

        })
        SpeciesList.num_new_entries = new_entries;

//        SpeciesList.insert_new_entry_spacer(new_entries);
        if (did_add) {
            vibrateDouble(this, 100, 250, 100);
        } else if (do_vibrate) {
            vibrate(this,100)
        }
//        if (new_entries > 0) {
            SpeciesList.update_list_on_ui_thread();
//        }

        MessageSender.messageLog.add(t_scored)
    }
}