package xyz.apiote.bimba.czwek.dashboard.ui.home

import android.content.Context
import android.net.ConnectivityManager
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import xyz.apiote.bimba.czwek.repo.TrafficResponseException
import xyz.apiote.bimba.czwek.repo.OnlineRepository
import xyz.apiote.bimba.czwek.repo.Queryable

class HomeViewModel : ViewModel() {
	private val mutableQueryables = MutableLiveData<List<Queryable>>()
	val queryables: LiveData<List<Queryable>> = mutableQueryables

	fun getQueryables(cm: ConnectivityManager, query: String, context: Context) {
		viewModelScope.launch {
			try {
				val repository = OnlineRepository()
				mutableQueryables.value = repository.queryQueryables(cm, query, context) ?: emptyList()
			} catch (e: TrafficResponseException) {
				// xxx intentionally no error showing in suggestions
				Log.e("Suggestion", "$e")
			}
		}
	}

	inner class SearchBarWatcher(
		private val context: Context, private val cm: ConnectivityManager
	) : TextWatcher {
		private val handler = Handler(Looper.getMainLooper())
		private var workRunnable = Runnable {}

		override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
		}

		override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
		}

		override fun afterTextChanged(s: Editable?) {
			handler.removeCallbacks(workRunnable)
			workRunnable = Runnable {
				val text = s.toString()
				getQueryables(cm, text, context)
			}
			handler.postDelayed(workRunnable, 750)
		}
	}
}