package com.centralcloud.oncall.ui

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.centralcloud.oncall.R
import com.centralcloud.oncall.db.*
import com.centralcloud.oncall.firebase.FirebaseMessenger
import com.centralcloud.oncall.up.Distributor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import androidx.core.net.toUri

class SubscriptionsViewModel(private val repository: Repository) : ViewModel() {
    fun list(): LiveData<List<Subscription>> {
        return repository.getSubscriptionsLiveData()
    }

    fun listIdsWithInstantStatus(): LiveData<Set<Pair<Long, Boolean>>> {
        return repository.getSubscriptionIdsWithInstantStatusLiveData()
    }

    fun add(subscription: Subscription) = viewModelScope.launch(Dispatchers.IO) {
        repository.addSubscription(subscription)
    }

    fun remove(context: Context, subscriptionId: Long) = viewModelScope.launch(Dispatchers.IO) {
        val subscription = repository.getSubscription(subscriptionId) ?: return@launch
        if (subscription.upAppId != null && subscription.upConnectorToken != null) {
            val distributor = Distributor(context)
            distributor.sendUnregistered(subscription.upAppId, subscription.upConnectorToken)
        }
        repository.removeSubscription(subscription)
        if (subscription.icon != null) {
            val resolver = context.applicationContext.contentResolver
            try {
                resolver.delete(subscription.icon.toUri(), null, null)
            } catch (_: Exception) {
                // Don't care
            }
        }
        // Unsubscribe from Firebase if this is the default oncall.hugo.dk server
        val appBaseUrl = context.getString(R.string.app_base_url)
        if (subscription.baseUrl == appBaseUrl) {
            val messenger = FirebaseMessenger()
            messenger.unsubscribe(subscription.topic)
        }
    }

    suspend fun get(baseUrl: String, topic: String): Subscription? {
        return repository.getSubscription(baseUrl, topic)
    }
}

class SubscriptionsViewModelFactory(private val repository: Repository) : ViewModelProvider.Factory {
    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T =
        with(modelClass){
            when {
                isAssignableFrom(SubscriptionsViewModel::class.java) -> SubscriptionsViewModel(repository) as T
                else -> throw IllegalArgumentException("Unknown viewModel class $modelClass")
            }
        }
}
