package ch.threema.app.preference.service

import android.content.Context
import ch.threema.app.R
import ch.threema.app.multidevice.MultiDeviceManager
import ch.threema.app.stores.PreferenceStore
import ch.threema.app.tasks.ReflectSettingsSyncTask
import ch.threema.base.utils.getThreemaLogger
import ch.threema.domain.taskmanager.Task
import ch.threema.domain.taskmanager.TaskCodec
import ch.threema.domain.taskmanager.TaskManager
import ch.threema.protobuf.d2d.sync.TypingIndicatorPolicy

private val logger = getThreemaLogger("TypingIndicatorPolicySetting")

/**
 * The (global) setting whether typing indicators should be sent. Stores true if they should be sent.
 */
class TypingIndicatorPolicySetting internal constructor(
    multiDeviceManager: MultiDeviceManager,
    taskManager: TaskManager,
    preferenceStore: PreferenceStore,
    context: Context,
) : SynchronizedBooleanSetting(
    preferenceKey = context.getString(preferenceKeyStringRes),
    preferenceStore = preferenceStore,
    multiDeviceManager = multiDeviceManager,
    taskManager = taskManager,
) {
    override fun instantiateReflectionTask(): Task<*, TaskCodec> =
        ReflectSettingsSyncTask.ReflectTypingIndicatorPolicySyncUpdate()

    fun getTypingIndicatorPolicy(): TypingIndicatorPolicy =
        when (get()) {
            true -> TypingIndicatorPolicy.SEND_TYPING_INDICATOR
            false -> TypingIndicatorPolicy.DONT_SEND_TYPING_INDICATOR
        }

    fun setFromSync(typingIndicatorPolicy: TypingIndicatorPolicy) {
        val value = when (typingIndicatorPolicy) {
            TypingIndicatorPolicy.SEND_TYPING_INDICATOR -> true
            TypingIndicatorPolicy.DONT_SEND_TYPING_INDICATOR -> false
            TypingIndicatorPolicy.UNRECOGNIZED -> {
                logger.warn("Cannot set unrecognized typing indicator policy")
                return
            }
        }

        setFromSync(value)
    }

    companion object {
        @JvmStatic
        val preferenceKeyStringRes = R.string.preferences__typing_indicator
    }
}
