package com.seven.ikar.kotlin.core.settings

import android.content.Context
import com.seven.ikar.kotlin.core.model.PrivacySettingsDto
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

data class PrivacyRuntimeSnapshot(
    val passcodeLockEnabled: Boolean = false,
    val showMessagePreview: Boolean = true
)

class AndroidPrivacyRuntimeSettings(context: Context) {
    private val preferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
    private val _snapshot = MutableStateFlow(loadSnapshot())
    val snapshot: StateFlow<PrivacyRuntimeSnapshot> = _snapshot.asStateFlow()

    fun loadSnapshot(): PrivacyRuntimeSnapshot =
        PrivacyRuntimeSnapshot(
            passcodeLockEnabled = preferences.getBoolean(KEY_PASSCODE_LOCK_ENABLED, false),
            showMessagePreview = preferences.getBoolean(KEY_SHOW_MESSAGE_PREVIEW, true)
        )

    fun saveFrom(settings: PrivacySettingsDto) {
        saveSnapshot(
            PrivacyRuntimeSnapshot(
                passcodeLockEnabled = settings.passcodeLockEnabled,
                showMessagePreview = settings.showMessagePreview
            )
        )
    }

    private fun saveSnapshot(snapshot: PrivacyRuntimeSnapshot) {
        preferences.edit()
            .putBoolean(KEY_PASSCODE_LOCK_ENABLED, snapshot.passcodeLockEnabled)
            .putBoolean(KEY_SHOW_MESSAGE_PREVIEW, snapshot.showMessagePreview)
            .apply()
        _snapshot.value = snapshot
    }

    companion object {
        private const val PREFERENCES_NAME = "ikar_kotlin_privacy_runtime"
        private const val KEY_PASSCODE_LOCK_ENABLED = "passcode_lock_enabled"
        private const val KEY_SHOW_MESSAGE_PREVIEW = "show_message_preview"
    }
}

class AppLockState {
    private val _isLocked = MutableStateFlow(false)
    val isLocked: StateFlow<Boolean> = _isLocked.asStateFlow()

    fun setLocked(locked: Boolean) {
        _isLocked.value = locked
    }
}
