package com.birdsounds.identify.presentation

import android.util.Log
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.snapshots.SnapshotStateList
import java.time.Instant


class AScore(
    _species: String,
    _score: Float,
    _timestamp: Long,

    ) {

    var split_stuff = _species.split("_")
    val species = split_stuff[0]
    val score = _score
    val common_name = split_stuff[1]
    val timestamp = _timestamp
    fun age(): Long {
        var tstamp: Long = Instant.now().toEpochMilli()
        return (tstamp - timestamp)
    }

    override fun toString(): String {
        var tstamp: Long = Instant.now().toEpochMilli()
        return common_name + "," + species + "," + score.toString() + ", " + (age() / 1000.0).toString() + "s ago"
    }
}


object SpeciesList {
    var internal_list = mutableListOf<AScore>()
    var do_add_observation = false
    var _list_on_ui: SnapshotStateList<MutableState<String>>? = null
    fun setSpeciecsShow_list(list_in: SnapshotStateList<MutableState<String>>) {
        _list_on_ui = list_in;
    }

    fun add_observation(species_in: AScore) {
        Log.w(TAG,"In add obsergation")
        do_add_observation = false
        var idx = 0
        var idx_replace = -1
        for (i in internal_list) {
            if (i.species == species_in.species) {
                do_add_observation = false
                idx_replace = idx
            }
            idx += 1
        }
        if (idx_replace >= 0) {
            Log.w(TAG, "Replacing")
            internal_list[idx_replace] = species_in //            _list_on_ui?.removeAt(idx_replace)
            //            _list_on_ui?.add(species_in);
            //            if (_list_on_ui != null) {
            //            _list_on_ui?.removeAt(idx_replace)
            //                _list_on_ui.add(idx_replace, species_in);
            //            }

        } else {
            internal_list.add(species_in)


        }

        internal_list = internal_list.sortedBy({ (it.age()) }).toMutableList()

        for ((index, value) in internal_list.withIndex()) {
            _list_on_ui?.get(index)?.value = value.common_name;
        }

        Log.w(TAG, internal_list.size.toString())
        Log.w(TAG, _list_on_ui?.size.toString()) //        internal_list.add(species_in)
    }

}