ContactEditViewModel.swift 56 lignes · 1594 octets
import Foundation
import UIKit

// Port of ui/contact/ContactEditViewModel.kt.

@MainActor
final class ContactEditViewModel: ObservableObject {
    @Published var card = ContactCard()
    @Published private(set) var profilePreview: UIImage?
    @Published private(set) var loaded = false
    @Published private(set) var saveDone = false

    let contactId: Int64

    private let repository: ContactRepository
    private var pendingProfile: UIImage?

    init(
        contactId: Int64,
        repository: ContactRepository = ContactRepository(
            dao: Card2vcfDatabase.shared.crmContactDao,
            images: ContactImageStore()
        )
    ) {
        self.contactId = contactId
        self.repository = repository
    }

    func load() async {
        guard !loaded else { return }
        guard let entity = try? await repository.getById(contactId) else { return }
        card = entity.toCard()
        if let path = entity.profileImagePath?.nilIfBlank {
            profilePreview = UIImage(contentsOfFile: path)
        }
        loaded = true
    }

    func setProfileImage(_ image: UIImage) {
        pendingProfile = image
        profilePreview = image
    }

    func save() {
        Task {
            let profilePath = pendingProfile.flatMap { DraftImageWriter.writeJpeg($0, prefix: "profile") }
            try? await repository.updateFromCard(
                id: contactId,
                card: card,
                profileImagePath: profilePath,
                preserveNotesIfBlankDraft: false
            )
            saveDone = true
        }
    }
}