# AuthRepo.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.domain.auth

    import android.content.Context
    import android.content.Intent
    import dk.nsp.api.auth.AuthController
    import dk.nsp.api.auth.OptionalKeyModelWithPotentialError
    import dk.nsp.shared.Failed
    import dk.nsp.shared.ResultWrapper
    import dk.nsp.shared.Success
    import dk.nsp.shared.mapSuccess
    import dk.nsp.shared.util.asyncDefault
    import dk.nsp.shared.util.launchDefault
    import kotlinx.coroutines.CoroutineScope
    import kotlinx.coroutines.Deferred
    import kotlinx.coroutines.Job
    import javax.crypto.Cipher

    class AuthRepo(context: Context) {
        private val authController = AuthController.get(context.applicationContext)

        fun haveLogin() = authController.hasLogin()

        fun clear() {
            clearSession()
            authController.clear()
        }

        fun logout() {
            authController.clearSession()
        }

        suspend fun getRegisterIntent(): ResultWrapper<Intent> {
            return authController.getRegisterIntent()
        }

        fun handleLoginResultAndGetAccessToken(
            scope: CoroutineScope,
            data: Intent?,
            onAccessToken: () -> Unit,
            onFailed: (error: RegistrationError) -> Unit
        ): Job = scope.launchDefault {
            when (val loginResult = authController.handleLoginResult(data)) {
                is Failed -> onFailed(loginResult.error.toRegistrationError())
                is Success -> {
                    // Login was a success, we should now be able to get an accessToken
                    when (val accessToken = authController.getAccessToken()) {
                        is Failed -> onFailed(accessToken.error.toRegistrationError())
                        is Success -> {
                            onAccessToken()
                        }
                    }
                }
            }
        }

        fun tryRestoreFromPassword(
            pinCode: String,
            scope: CoroutineScope
        ): Deferred<OptionalKeyModelWithPotentialErrorLogic> = scope.asyncDefault {
            authController.tryRestoreFromPassword(pinCode).toLogic()
        }

        fun loginWithNewPin(
            pinCode: String,
            scope: CoroutineScope
        ): Deferred<ResultWrapper<KeyModel>> = scope.asyncDefault {
            authController.storeRefreshTokenAndKeyId(pinCode).mapSuccess { it.toLogic() }
        }

        fun tryRestoreFromBiometric(
            crypto: Cipher,
            scope: CoroutineScope
        ) = scope.asyncDefault {
            authController.tryRestoreFromBiometric(crypto).toLogic()
        }

        fun storeLongSecretViaBiometric(
            cipher: Cipher,
            keyModel: KeyModel
        ): ResultWrapper<Unit> =
            authController.storeLongSecretViaBiometric(cipher, keyModel.toDTO())

        fun removeLongSecretStoredViaBiometric() {
            authController.removeLongSecretStoredViaBiometric()
        }

        fun isLoggedIn(): Boolean =
            authController.isLoggedIn()

        fun clearSession() {
            authController.clearSession()
        }
    }

    class OptionalKeyModelWithPotentialErrorLogic(
        val keyModelResult: ResultWrapper<KeyModel>,
        val optionalKeyModel: KeyModel? = null
    )

    fun OptionalKeyModelWithPotentialError.toLogic(): OptionalKeyModelWithPotentialErrorLogic {

        return OptionalKeyModelWithPotentialErrorLogic(
            this.keyModelResult.mapSuccess { it.toLogic() },
            optionalKeyModel?.toLogic()
        )
    }

    fun OptionalKeyModelWithPotentialErrorLogic.toDTO(): OptionalKeyModelWithPotentialError {
        return OptionalKeyModelWithPotentialError(
            this.keyModelResult.mapSuccess { it.toDTO() },
            optionalKeyModel?.toDTO()
        )
    }