import Foundation

extension Content {

    func saveToDisk() -> Bool {
        guard didLoadContent else { return false }
        guard storage.contentScope != nil else {
            print("Storage not initialized, not saving content")
            return false
        }

        var failedSaves = 0
        failedSaves += pages.count { !storage.save(pageMetadata: $0.data, for: $0.id) }
        failedSaves += posts.count { !storage.save(post: $0.data, for: $0.id) }
        failedSaves += tags.count { !storage.save(tagMetadata: $0.data, for: $0.id) }
        failedSaves.increment(!storage.save(settings: settings.data(tagOverview: tagOverview)))
        failedSaves += files.count { !storage.save(fileInfo: $0.data, for: $0.id) }

        if failedSaves > 0 {
            print("Save partially failed with \(failedSaves) errors")
            return false
        }
        return true
    }

    func removeUnlinkedFiles() -> Bool {
        var success = true
        if !storage.deletePostFiles(notIn: posts.map { $0.id }) {
            success = false
        }
        if !storage.deletePageFiles(notIn: pages.map { $0.id }) {
            success = false
        }
        if !storage.deleteTagFiles(notIn: tags.map { $0.id }) {
            success = false
        }
        if !storage.deleteFileResources(notIn: files.map { $0.id }) {
            success = false
        }
        return success
    }
}
