import Foundation
import Combine

class ChangeObservingItem: ObservableContentItem {
    
    unowned let content: Content
    
    /// A dummy property to force views to update when properties change
    @Published
    private var changeToggle = false

    private var shouldSave = true

    var cancellables = Set<AnyCancellable>()
    
    init(content: Content) {
        self.content = content
        
        observeChanges()
    }
    
    // MARK: Change observation
    
    func didChange(save: Bool = true) {
        DispatchQueue.main.async {
            self.shouldSave = save
            self.changeToggle.toggle()
            self.shouldSave = true
        }
    }

    func needsSaving() {
        guard shouldSave else {
            return
        }
        content.needsSave()
    }
}
