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

import Foundation
import CoreData
import Pachyderm
import UserAccounts

@objc(AccountPreferences)
public final class AccountPreferences: NSManagedObject {
    
    @nonobjc class func fetchRequest(account: UserAccountInfo) -> NSFetchRequest<AccountPreferences> {
        let req = NSFetchRequest<AccountPreferences>(entityName: "AccountPreferences")
        req.predicate = NSPredicate(format: "accountID = %@", account.id)
        req.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
        return req
    }
    
    @NSManaged public var accountID: String
    @NSManaged var createdAt: Date
    @NSManaged var pinnedTimelinesData: Data?
    @NSManaged var serverDefaultFederation: Bool
    @NSManaged var serverDefaultLanguage: String?
    @NSManaged private var serverDefaultVisibilityString: String?
    
    @LazilyDecoding(from: \AccountPreferences.pinnedTimelinesData, fallback: AccountPreferences.defaultPinnedTimelines)
    var pinnedTimelines: [PinnedTimeline]
    
    var serverDefaultVisibility: Visibility? {
        get {
            serverDefaultVisibilityString.flatMap(Visibility.init(rawValue:))
        }
        set {
            serverDefaultVisibilityString = newValue?.rawValue
        }
    }
    
    static func `default`(account: UserAccountInfo, context: NSManagedObjectContext) -> AccountPreferences {
        let prefs = AccountPreferences(context: context)
        prefs.accountID = account.id
        prefs.createdAt = Date()
        prefs.pinnedTimelines = Self.defaultPinnedTimelines
        return prefs
    }
    
    private static let defaultPinnedTimelines = [PinnedTimeline.home, .public(local: true), .public(local: false)]
    
}
