package com.vpn.fastestvpnservice.viewmodels

import android.content.Context
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import com.vpn.fastestvpnservice.beans.Server
import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper

class SearchListViewModel constructor(context: Context, serverListViewModel: ServerListViewModel): ViewModel() {

    private var serverListViewModel: ServerListViewModel

    init {
        this.serverListViewModel = serverListViewModel
    }

    private var _searchText = MutableLiveData<String>("")
    var searchText: LiveData<String> = _searchText

    private var _isActive = MutableLiveData<Boolean>(false)
    var isActive: LiveData<Boolean> = _isActive


    val basePreferenceHelper = BasePreferenceHelper(context)

    private var _countriesList = MutableLiveData<ArrayList<Server>>(getCountries())
    var countriesList: LiveData<ArrayList<Server>> = _countriesList

    fun searchTextChange(text: String) {
        _searchText.value = text

        _countriesList.value = getCountries()
    }

    fun isActiveChange(state: Boolean) {
        _isActive.value = state

        if (_isActive.value == false) {
            searchTextChange("")
        }
    }

    fun getCountries(): ArrayList<Server> {
        val serversData = basePreferenceHelper.getServerData()
        val allServers: ArrayList<Server> = ArrayList<Server>()
        val serversArray: ArrayList<Server> = ArrayList<Server>()
        var filtersArray: ArrayList<Server> = ArrayList<Server>()

        serversData.forEachIndexed { index, serverData ->
            serverData.servers?.forEachIndexed { indexes, server ->
                allServers.add(indexes, server)
            }
        }

        val searchServersList = serverListViewModel.filterServersAllCategory(allServers)

        searchServersList.forEachIndexed { index, server ->
            if (server.country?.lowercase()?.contains(_searchText.value?.lowercase().toString()) == true
                || server.server_name?.lowercase()?.contains(_searchText.value?.lowercase().toString()) == true
                || server.name?.lowercase()?.contains(_searchText.value?.lowercase().toString()) == true
                || server.iso?.lowercase()?.contains(_searchText.value?.lowercase().toString()) == true) {
                serversArray.add(server)
            }
        }

        filtersArray = if (serversArray.size > 0) {
            serversArray
        } else {
            searchServersList
        }
        Log.d("test_search", searchServersList.size.toString())
        return filtersArray

    }

}