//
//  RelationshipMO.swift
//  Tusker
//
//  Created by Shadowfacts on 10/11/20.
//  Copyright © 2020 Shadowfacts. All rights reserved.
//

import Foundation
import CoreData
import Pachyderm

@objc(RelationshipMO)
public final class RelationshipMO: NSManagedObject, RelationshipProtocol {
    
    @nonobjc public class func fetchRequest() -> NSFetchRequest<RelationshipMO> {
        return NSFetchRequest<RelationshipMO>(entityName: "Relationship")
    }
    
    @NSManaged public var accountID: String
    @NSManaged public var blocking: Bool
    @NSManaged public var domainBlocking: Bool
    @NSManaged public var endorsed: Bool
    @NSManaged public var followedBy: Bool
    @NSManaged public var following: Bool
    @NSManaged public var muting: Bool
    @NSManaged public var mutingNotifications: Bool
    @NSManaged public var requested: Bool
    @NSManaged public var showingReblogs: Bool
    @NSManaged public var account: AccountMO?
    
    public var followRequested: Bool { requested }
    
}

extension RelationshipMO {
    convenience init(apiRelationship relationship: Relationship, container: MastodonCachePersistentStore, context: NSManagedObjectContext) {
        self.init(context: context)
        self.updateFrom(apiRelationship: relationship, container: container)
    }
    
    func updateFrom(apiRelationship relationship: Relationship, container: MastodonCachePersistentStore) {
        guard let context = managedObjectContext else {
            // we have been deleted, don't bother updating
            return
        }
        
        self.accountID = relationship.accountID
        self.blocking = relationship.blocking
        self.domainBlocking = relationship.domainBlocking
        self.endorsed = relationship.endorsed
        self.followedBy = relationship.followedBy
        self.following = relationship.following
        self.muting = relationship.muting
        self.mutingNotifications = relationship.mutingNotifications
        self.requested = relationship.followRequested
        self.showingReblogs = relationship.showingReblogs
        
        self.account = container.account(for: relationship.accountID, in: context)
    }
}
