Skip to content
Snippets Groups Projects
AccountDeleteViewModel.swift 1.29 KiB
Newer Older
Bruno Muniz's avatar
Bruno Muniz committed
import HUD
import Combine
Bruno Muniz's avatar
Bruno Muniz committed
import Defaults
Bruno Muniz's avatar
Bruno Muniz committed
import Foundation
Bruno Muniz's avatar
Bruno Muniz committed
import XXClient
import XXMessengerClient
Bruno Muniz's avatar
Bruno Muniz committed
import DependencyInjection
Bruno Muniz's avatar
Bruno Muniz committed
import Models
Bruno Muniz's avatar
Bruno Muniz committed

final class AccountDeleteViewModel {
Bruno Muniz's avatar
Bruno Muniz committed
    @Dependency var messenger: Messenger

    @KeyObject(.username, defaultValue: nil) var username: String?

Bruno Muniz's avatar
Bruno Muniz committed
    var deleting = false

    var hud: AnyPublisher<HUDStatus, Never> { hudRelay.eraseToAnyPublisher() }
    private let hudRelay = CurrentValueSubject<HUDStatus, Never>(.none)

    func didTapDelete() {
        guard deleting == false else { return }
        deleting = true

        DispatchQueue.main.async { [weak self] in
Bruno Muniz's avatar
Bruno Muniz committed
            self?.hudRelay.send(.on)
Bruno Muniz's avatar
Bruno Muniz committed
        }

        do {
Bruno Muniz's avatar
Bruno Muniz committed
            let fact = Fact(fact: username!, type: FactType.username.rawValue)
            try messenger.ud.get()!.permanentDeleteAccount(username: fact)
            try messenger.destroy()

Bruno Muniz's avatar
Bruno Muniz committed
            DispatchQueue.main.async { [weak self] in
                self?.hudRelay.send(.error(.init(
                    content: "Now kill the app and re-open",
                    title: "Account deleted",
                    dismissable: false
                )))
            }
        } catch {
            DispatchQueue.main.async { [weak self] in
                self?.hudRelay.send(.error(.init(with: error)))
            }
        }
    }
}