# SharedPrefsHelper.kt

    /*
     * The MIT License
     *
     * Original work sponsored and donated by The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     * Copyright (C) 2021 The Danish Health Data Authority (http://www.sundhedsdatastyrelsen.dk)
     *
     *
     * Permission is hereby granted, free of charge, to any person obtaining a copy of
     * this software and associated documentation files (the "Software"), to deal in
     * the Software without restriction, including without limitation the rights to
     * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
     * of the Software, and to permit persons to whom the Software is furnished to do
     * so, subject to the following conditions:
     *
     *
     * The above copyright notice and this permission notice shall be included in all
     * copies or substantial portions of the Software.
     *
     *
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
     * SOFTWARE.
     */

    package dk.nsp.shared.util.sharedprefs

    import android.content.Context
    import android.content.SharedPreferences
    import androidx.core.content.edit
    import dk.nsp.mingraviditet.util.extensions.isBeforeNow
    import dk.nsp.shared.tryAndLog
    import java.time.LocalDateTime
    import java.time.ZoneOffset

    class SharedPrefsHelper(
        context: Context,
        settingsName: String = defaultPreferencesName
    ) {

        private val sharedPref = context.getSharedPreferences(settingsName, Context.MODE_PRIVATE)

        //region Biometric
        /**
         * should we use fingerprint ?
         */
        var useBiometrics: Boolean?
            get() = get(usesFingerprintKey, false)
            set(value) = storeOrClear(usesFingerprintKey, value)

        /**
         * whenever we have asked the user to use fingerprint
         */
        var askedForUseBiometrics: Boolean?
            get() = get(askedForUseFingerprint, false)
            set(value) = storeOrClear(askedForUseFingerprint, value)

        fun clearBiometricSettings() {
            useBiometrics = null
            askedForUseBiometrics = null
        }
        //endregion

        /**
         * Screen security
         */
        var allowScreenshots: Boolean?
            get() = get(allowScreenshotsEnabledKey, true)
            set(value) = storeOrClear(allowScreenshotsEnabledKey, value)

        //region Data card
        var lastSelectedDataCardId: String?
            get() = get(lastSelectedDataCardKey, null)
            set(value) = store(lastSelectedDataCardKey, value)

        var dataCardNoCoursesWarningShown: Boolean?
            get() = get(dataCardNoCoursesWarningShownKey, false)
            set(value) = storeOrClear(dataCardNoCoursesWarningShownKey, value)

        var dataCardNoActiveCourseWarningShown: Boolean?
            get() = get(dataCardNoActiveCourseWarningShownKey, false)
            set(value) = storeOrClear(dataCardNoActiveCourseWarningShownKey, value)
        //endregion

        fun clearAllPreferences() {
            sharedPref.edit(commit = true) { clear() }
        }

        //region Common read/write shorthands
        //region Store functions
        fun store(forKey: String, value: String?) = sharedPref.applyWith { putString(forKey, value) }
        fun store(forKey: String, value: Int) = sharedPref.applyWith { putInt(forKey, value) }
        fun store(forKey: String, value: Long) = sharedPref.applyWith { putLong(forKey, value) }
        fun store(forKey: String, value: Boolean) = sharedPref.applyWith { putBoolean(forKey, value) }
        //endregion

        //region Destructive store
        private fun storeOrClear(forKey: String, value: Boolean?) {
            if (value == null) {
                remove(forKey)
            } else {
                store(forKey, value)
            }
        }
        //endregion

        //region Fetch functions
        fun get(forKey: String, default: String? = null) = sharedPref.getString(forKey, default)
        fun get(forKey: String, default: Int) = sharedPref.getInt(forKey, default)
        fun get(forKey: String, default: Long) = sharedPref.getLong(forKey, default)
        fun get(forKey: String, default: Boolean) = sharedPref.getBoolean(forKey, default)
        //endregion

        fun hasValue(forKey: String) = sharedPref.contains(forKey)

        fun remove(forKey: String) = sharedPref.applyWith { remove(forKey) }
        //endregion

        //region Force delay documentation sending
        private val sendBlockingBufferInSeconds = 15 * 60L

        //region Documentation for personal
        fun getLastSentPersonalDocumentation(episodeOfCareId: String) = LocalDateTime.ofEpochSecond(
            get(lastSentPersonalDocumentationKey + episodeOfCareId, 0L),
            0,
            ZoneOffset.UTC
        )

        fun setSentPersonalDocumentation(episodeOfCareId: String) = store(
            lastSentPersonalDocumentationKey + episodeOfCareId,
            LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)
        )

        fun allowSendPersonalDocumentation(episodeOfCareId: String) =
            getLastSentPersonalDocumentation(episodeOfCareId).isBeforeNow(bySeconds = sendBlockingBufferInSeconds)
        //endregion

        //region Documentation for employer
        fun getLastSentEmployerDocumentation(episodeOfCareId: String) = LocalDateTime.ofEpochSecond(
            get(lastSentEmployerDocumentationKey+episodeOfCareId, 0L),
            0,
            ZoneOffset.UTC
        )
        fun setSentEmployerDocumentation(episodeOfCareId: String) = store(
            lastSentEmployerDocumentationKey + episodeOfCareId,
            LocalDateTime.now().toEpochSecond(ZoneOffset.UTC)
        )
        fun allowSendEmployerDocumentation(episodeOfCareId: String) =
            getLastSentEmployerDocumentation(episodeOfCareId).isBeforeNow(bySeconds = sendBlockingBufferInSeconds)
        //endregion
        //endregion

        companion object {
            private const val usesFingerprintKey = "UsesFingerprintPreference"
            private const val askedForUseFingerprint = "AskedForUseFingerprintPreference"
            private const val allowScreenshotsEnabledKey = "screenSecurityEnabledPreference"
            private const val lastSelectedDataCardKey = "lastSelectedDataCardKey"
            private const val dataCardNoCoursesWarningShownKey = "dataCardNoCoursesWarningShown"
            private const val dataCardNoActiveCourseWarningShownKey =
                "dataCardNoActiveCourseWarningShownKey"

            //region Documentation send buffer keys
            private const val lastSentPersonalDocumentationKey = "lastSentPersonalDocumentationKey_"
            private const val lastSentEmployerDocumentationKey = "lastSentEmployerDocumentationKey_"
            //endregion

            const val defaultPreferencesName = "MinGraviditetAppPrefs"
        }
    }

    fun Context.getDefaultSharedPrefs() = SharedPrefsHelper(this)

    private inline fun SharedPreferences.applyWith(crossinline action: (SharedPreferences.Editor.() -> Unit)) {
        tryAndLog {
            edit().apply(action).apply()
        }
    }