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.api.*

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

	fun getQueryables(cm: ConnectivityManager, server: Server, query: String) {
		viewModelScope.launch {
			val result = queryQueryables(cm, server, query, limit = 6)
			if (result.error != null) {
				// note intentionally no error showing in suggestions
				if (result.stream != null) {
					Log.e("Suggestion", "${b2s(result.stream.readBytes())}")
					return@launch
					Log.e(
						"Suggestion",
						"${result.error.statusCode}, ${ErrorResponse.unmarshal(result.stream).message}"
					)
				} else {
					Log.e("Suggestion", "${result.error.statusCode}")
				}
			} else {
				mutableQueryables.value =
					when (val response = QueryablesResponse.unmarshal(result.stream!!)) {
						is QueryablesResponseDev -> response.queryables
						is QueryablesResponseV1 -> response.queryables
						else -> null
					}
			}
		}
	}

	private fun b2s(b: ByteArray): String {
		var s = ""
		b.forEach {
			if (it in 32..127) {
				s += Char(it.toInt())
			} else {
				s += "\\x$it"
			}
		}
		return s
	}

	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,
					Server.get(context), text
				)
			}
			handler.postDelayed(
				workRunnable,
				750
			) // todo(ux,low) make good time (probably between 500, 1000ms)
		}
	}
}