//
//  Draft.swift
//  ComposeUI
//
//  Created by Shadowfacts on 4/22/23.
//

import CoreData
import Pachyderm

@objc
public class Draft: NSManagedObject, Identifiable {
    @nonobjc public class func fetchRequest() -> NSFetchRequest<Draft> {
        return NSFetchRequest<Draft>(entityName: "Draft")
    }
    
    @nonobjc public class func fetchRequest(id: UUID) -> NSFetchRequest<Draft> {
        let req = NSFetchRequest<Draft>(entityName: "Draft")
        req.predicate = NSPredicate(format: "id = %@", id as NSUUID)
        return req
    }
    
    @NSManaged public var accountID: String
    @NSManaged public var contentWarning: String
    @NSManaged public var contentWarningEnabled: Bool
    @NSManaged public var editedStatusID: String?
    @NSManaged public var id: UUID
    @NSManaged public var initialContentWarning: String?
    @NSManaged public var initialText: String
    @NSManaged public var inReplyToID: String?
    @NSManaged public var language: String? // ISO 639 language code
    @NSManaged public var lastModified: Date!
    @NSManaged public var localOnly: Bool
    @NSManaged public var text: String
    @NSManaged private var visibilityStr: String
    
    @NSManaged internal var attachments: NSMutableOrderedSet
    @NSManaged public var poll: Poll?
    
    public var visibility: Visibility {
        get {
            Visibility(rawValue: visibilityStr) ?? .public
        }
        set {
            visibilityStr = newValue.rawValue
        }
    }
    
    public var draftAttachments: [DraftAttachment] {
        get {
            attachments.array as! [DraftAttachment]
        }
        set {
            attachments = NSMutableOrderedSet(array: newValue)
        }
    }
    
    public override func awakeFromInsert() {
        super.awakeFromInsert()
        id = UUID()
        lastModified = Date()
    }
    
}

extension Draft {
    public var hasContent: Bool {
        (!text.isEmpty && text != initialText) ||
            (contentWarningEnabled && !contentWarning.isEmpty && contentWarning != initialContentWarning) ||
            attachments.count > 0 ||
            poll?.hasContent == true
    }
}
