Impressia/Vernissage/CoreData/AccountDataHandler.swift

71 lines
2.3 KiB
Swift
Raw Normal View History

2022-12-31 16:31:05 +01:00
//
// https://mczachurski.dev
// Copyright © 2022 Marcin Czachurski and the repository contributors.
// Licensed under the MIT License.
//
import Foundation
2023-01-11 13:16:43 +01:00
import CoreData
2022-12-31 16:31:05 +01:00
class AccountDataHandler {
2023-01-05 11:55:20 +01:00
public static let shared = AccountDataHandler()
private init() { }
2023-01-11 13:16:43 +01:00
func getAccountsData(viewContext: NSManagedObjectContext? = nil) -> [AccountData] {
let context = viewContext ?? CoreDataHandler.shared.container.viewContext
2022-12-31 16:31:05 +01:00
let fetchRequest = AccountData.fetchRequest()
do {
return try context.fetch(fetchRequest)
} catch {
2023-01-15 12:41:55 +01:00
ErrorService.shared.handle(error, message: "Accounts cannot be retrieved (getAccountsData).")
2022-12-31 16:31:05 +01:00
return []
}
}
2023-01-01 18:13:36 +01:00
2023-01-11 13:16:43 +01:00
func getCurrentAccountData(viewContext: NSManagedObjectContext? = nil) -> AccountData? {
let accounts = self.getAccountsData(viewContext: viewContext)
2023-01-05 11:55:20 +01:00
let defaultSettings = ApplicationSettingsHandler.shared.getDefaultSettings()
2023-01-01 18:13:36 +01:00
let currentAccount = accounts.first { accountData in
accountData.id == defaultSettings.currentAccount
}
if let currentAccount {
return currentAccount
}
return accounts.first
}
2022-12-31 16:31:05 +01:00
2023-01-11 13:16:43 +01:00
func getAccountData(accountId: String, viewContext: NSManagedObjectContext? = nil) -> AccountData? {
let context = viewContext ?? CoreDataHandler.shared.container.viewContext
let fetchRequest = AccountData.fetchRequest()
fetchRequest.fetchLimit = 1
fetchRequest.predicate = NSPredicate(format: "id = %@", accountId)
do {
return try context.fetch(fetchRequest).first
} catch {
2023-01-15 12:41:55 +01:00
ErrorService.shared.handle(error, message: "Error during fetching status (getAccountData).")
2023-01-11 13:16:43 +01:00
return nil
}
}
2023-01-27 17:31:28 +01:00
func remove(accountData: AccountData) {
let context = CoreDataHandler.shared.container.viewContext
context.delete(accountData)
do {
try context.save()
} catch {
ErrorService.shared.handle(error, message: "Error during deleting account data (remove).")
}
}
2022-12-31 16:31:05 +01:00
func createAccountDataEntity() -> AccountData {
let context = CoreDataHandler.shared.container.viewContext
return AccountData(context: context)
}
}