package com.tapjoy.easyapp

import android.content.SharedPreferences
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import org.json.JSONArray
import org.json.JSONException

const val AUTO_CONNECT_KEY = "autoConnectKey"
const val PREF_SDK_LIST_KEY = "sdkKeyList"
const val PREF_SDK_CURRENT_KEY = "sdkCurrentKey"
const val DEFAULT_SDK_KEY = "u6SfEbh_TA-WMiGqgQ3W8QECyiQIURFEeKm0zbOggubusy-o5ZfXp33sTXaD"

class ConfigViewModel : ViewModel() {

    private val _sdkKeyInput = MutableStateFlow("")
    private val _statusMessage = MutableStateFlow("Restart the app to connect with the new key")
    private val _checked = MutableStateFlow(true)
    private val _sdksList = MutableStateFlow(listOf<String>())
    val sdkKeyInput = _sdkKeyInput.asStateFlow()
    val statusMessage = _statusMessage.asStateFlow()
    val checked = _checked.asStateFlow()
    val sdksList = _sdksList.asStateFlow()

    fun initSdksList(preferences: SharedPreferences) {
        val sdks: List<String> = getListOfSdkKeysFromCache(preferences).filterNotNull()
        if (sdks.isNotEmpty()) {
            _sdkKeyInput.value = sdks.first()
        }
        _checked.value = preferences.getBoolean(AUTO_CONNECT_KEY, true)
        _sdksList.value = sdks
    }

    fun onSdkItemSelected(preferences: SharedPreferences, sdkKey: String) {
        setCurrentSdkKey(preferences, sdkKey)
        _sdkKeyInput.value = sdkKey
    }

    fun addSdkKeyClicked(preferences: SharedPreferences) {
        val sdk: String = _sdkKeyInput.value
        if (sdk.length < 50) {
            _statusMessage.value = "Not enough characters"
            return
        }
        addNewSdkKeyToCache(preferences, sdk)
        setCurrentSdkKey(preferences, sdk)
        val sdks: List<String> = getListOfSdkKeysFromCache(preferences).filterNotNull()
        _sdksList.value = sdks
        _statusMessage.value = "Restart the app to connect with the new key"
    }

    private fun setCurrentSdkKey(preferences: SharedPreferences, sdkKey: String) {
        preferences.edit().putString(PREF_SDK_CURRENT_KEY, sdkKey).apply()
    }

    private fun addNewSdkKeyToCache(preferences: SharedPreferences, s: String) {
        val currentList = getListOfSdkKeysFromCache(preferences)
        currentList.remove(s)
        currentList.add(0, s)
        val jsArray = JSONArray(currentList)
        preferences.edit().putString(PREF_SDK_CURRENT_KEY, s).apply()
        preferences.edit().putString(PREF_SDK_LIST_KEY, jsArray.toString()).apply()
    }

    private fun getListOfSdkKeysFromCache(preferences: SharedPreferences): ArrayList<String?> {
        val currentList = ArrayList<String?>()
        try {
            val jArray = JSONArray(preferences.getString(PREF_SDK_LIST_KEY, "[]"))
            for (i in 0 until jArray.length()) {
                currentList.add(jArray.getString(i))
            }
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        // If nothing save in cache add the default sdk key
        return if (currentList.isEmpty()) {
            val arrayList = ArrayList<String?>()
            arrayList.add(DEFAULT_SDK_KEY)
            arrayList
        } else {
            currentList
        }
    }

    fun setAutoConnect(preferences: SharedPreferences) {
        _checked.value = !checked.value
        if (checked.value) {
            _statusMessage.value = "Restart the app to auto connect"
        } else {
            _statusMessage.value = "Restart the app to connect manually"
        }
        preferences.edit().putBoolean(AUTO_CONNECT_KEY, checked.value).apply()
    }

    fun setSdkInput(input: String) {
        _sdkKeyInput.value = input
    }
}
