package de.sebse.fuplanner2.auth

import android.content.Context
import de.sebse.fuplanner2.blackboard.Blackboard
import de.sebse.fuplanner2.blackboard.BlackboardInfo
import de.sebse.fuplanner2.database.AppDatabase
import de.sebse.fuplanner2.database.User
import de.sebse.fuplanner2.utils.console
import de.sebse.fuplanner2.whiteboard.Whiteboard
import de.sebse.fuplanner2.whiteboard.WhiteboardInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object FuplannerAccountHelper {
    suspend fun authenticate(
        ctx: Context,
        name: String,
        password: String,
        addNewUser: Boolean
    ): String {
        val database = AppDatabase.getInstance()
        if (addNewUser) {
            console.warn("Previous user account will be removed!")
            removeAccount(name)
        }
        val user = database.userDao().findByUsername(name) ?: User(
            cookies = UserCookies(),
            bbInfo = BlackboardInfo(),
            wbInfo = WhiteboardInfo(),
            userName = name
        )

        var available = Blackboard.isAvailable(ctx, name)
        if (available)
            Blackboard.login(ctx, name, password, user)

        available = Whiteboard.isAvailable(ctx, name)
        if (available) {
            Whiteboard.login(ctx, name, password, user)
        }

        database.userDao().upsert(user)

        return user.toString()
    }

    fun getTokenType(userId: String): String {
        return FuplannerAccountConstants.FU_ACC_TOKEN_TYPE
    }

    suspend fun removeAccount(userName: String) {
        val database = AppDatabase.getInstance()
        withContext(Dispatchers.Default) {
            database.userDao().deleteByUserName(userName)
        }
    }

}
