import Foundation
import TigaseSwift

open class AccountManagerScramSaltedPasswordCache: ScramSaltedPasswordCacheProtocol {
    public init() {
    }

    public func getSaltedPassword(for sessionObject: SessionObject, id: String) -> [UInt8]? {
        guard let salted = AccountManager.getAccount(for: sessionObject)?.saltedPassword else {
            return nil
        }
        return salted.id == id ? salted.value : nil
    }

    public func store(for sessionObject: SessionObject, id: String, saltedPassword: [UInt8]) {
        setSaltedPassword(AccountManager.SaltEntry(id: id, value: saltedPassword), for: sessionObject)
    }

    public func clearCache(for sessionObject: SessionObject) {
        setSaltedPassword(nil, for: sessionObject)
    }

    fileprivate func setSaltedPassword(_ value: AccountManager.SaltEntry?, for sessionObject: SessionObject) {
        guard let account = AccountManager.getAccount(for: sessionObject) else {
            return
        }

        account.saltedPassword = value
        AccountManager.save(account: account)
    }
}
