Files
sodalive-ios/SodaLive/Sources/Settings/SignOut/SignOutViewModel.swift
2025-12-19 21:43:32 +09:00

78 lines
2.7 KiB
Swift

//
// SignOutViewModel.swift
// SodaLive
//
// Created by klaus on 2023/08/10.
//
import Foundation
import Combine
final class SignOutViewModel: ObservableObject {
private let repository = UserRepository()
private var subscription = Set<AnyCancellable>()
let reasons = I18n.Settings.SignOut.reasons
@Published var reasonSelectedIndex = -1
@Published var reason = ""
@Published var password = ""
@Published var errorMessage = ""
@Published var isShowPopup = false
@Published var isLoading = false
func signOut() {
if validate() {
isLoading = true
let reason = reasonSelectedIndex == reasons.count - 1 ? self.reason : reasons[reasonSelectedIndex]
repository.signOut(reason: reason, password: password.trimmingCharacters(in: .whitespacesAndNewlines))
.sink { result in
switch result {
case .finished:
DEBUG_LOG("finish")
case .failure(let error):
ERROR_LOG(error.localizedDescription)
}
} receiveValue: { [unowned self] response in
self.isLoading = false
let responseData = response.data
do {
let jsonDecoder = JSONDecoder()
let decoded = try jsonDecoder.decode(ApiResponseWithoutData.self, from: responseData)
if decoded.success {
UserDefaults.reset()
AppState.shared.isRestartApp = true
AppState.shared.setAppStep(step: .splash)
} else {
if let message = decoded.message {
self.errorMessage = message
} else {
self.errorMessage = I18n.Common.commonError
}
self.isShowPopup = true
}
} catch {
self.errorMessage = I18n.Common.commonError
self.isShowPopup = true
}
}
.store(in: &subscription)
}
}
private func validate() -> Bool {
if reasonSelectedIndex < 0 || (reasonSelectedIndex == reasons.count - 1 && self.reason.trimmingCharacters(in: .whitespaces).isEmpty) {
errorMessage = I18n.Settings.SignOut.selectReasonRequired
isShowPopup = true
return false
}
return true
}
}