//
//  ListMO.swift
//  Tusker
//
//  Created by Shadowfacts on 12/20/22.
//  Copyright © 2022 Shadowfacts. All rights reserved.
//

import Foundation
import CoreData
import Pachyderm

@objc(ListMO)
public final class ListMO: NSManagedObject, ListProtocol {
    
    @nonobjc public class func fetchRequest() -> NSFetchRequest<ListMO> {
        return NSFetchRequest(entityName: "List")
    }
    
    @nonobjc public class func fetchRequest(id: String) -> NSFetchRequest<ListMO> {
        let req = NSFetchRequest<ListMO>(entityName: "List")
        req.predicate = NSPredicate(format: "id = %@", id)
        return req
    }
    
    @NSManaged public var id: String
    @NSManaged public var title: String
    @NSManaged private var replyPolicyString: String?
    @NSManaged private var exclusiveInternal: Bool
    
    public var replyPolicy: List.ReplyPolicy? {
        get {
            replyPolicyString.flatMap(List.ReplyPolicy.init(rawValue:))
        }
        set {
            replyPolicyString = newValue?.rawValue
        }
    }
    
    public var exclusive: Bool? {
        get { exclusiveInternal }
        set { exclusiveInternal = newValue ?? false }
    }
    
}

extension ListMO {
    convenience init(apiList list: List, context: NSManagedObjectContext) {
        self.init(context: context)
        self.updateFrom(apiList: list)
    }
    
    func updateFrom(apiList list: List) {
        self.id = list.id
        self.title = list.title
        self.replyPolicy = list.replyPolicy
        self.exclusive = list.exclusive
    }
    
    var apiList: List {
        List(
            id: id,
            title: title,
            replyPolicy: replyPolicy,
            exclusive: exclusive
        )
    }
}
