//
//  BroadcastExtension.swift
//  WoWonder
//
//  Created by iMac on 16/05/24.
//  Copyright © 2024 ScriptSun. All rights reserved.
//

import Foundation

extension Broadcast: CoreDataObject {
    
    private static var fetcher: CoreDataFetcher<Broadcast> {
        get {
            return CoreDataFetcher<Broadcast>()
        }
    }
    
    convenience init(broadcast: BroadcastData) {
        self.init(context: CoreDataManager.getInstance().context)
        self.broadcast_id = Int32(broadcast.id ?? 0)
        self.user_id = Int32(broadcast.user_id ?? 0)
        self.name = broadcast.name
        self.image = broadcast.image
        self.time = Int32(broadcast.time ?? 0)
        self.org_image = broadcast.org_image
        for user in broadcast.users ?? [] {
            self.addToUsers(Users(user: user))
        }
    }
    
    func updateBroadcast(_ broadcast: BroadcastData) {
        self.broadcast_id = Int32(broadcast.id ?? 0)
        self.user_id = Int32(broadcast.user_id ?? 0)
        self.name = broadcast.name
        self.image = broadcast.image
        self.time = Int32(broadcast.time ?? 0)
        self.org_image = broadcast.org_image
        
        for user in self.getUsers() {
            self.removeFromUsers(user)
        }
        
        for user in broadcast.users ?? [] {
            self.addToUsers(Users(user: user))
        }
        self.save()
    }
    
    func save() {
        self.setValue(broadcast_id, forKey: #keyPath(Broadcast.broadcast_id))
        self.setValue(user_id, forKey: #keyPath(Broadcast.user_id))
        self.setValue(name, forKey: #keyPath(Broadcast.name))
        self.setValue(image, forKey: #keyPath(Broadcast.image))
        self.setValue(time, forKey: #keyPath(Broadcast.time))
        self.setValue(org_image, forKey: #keyPath(Broadcast.org_image))
        do {
            try self.managedObjectContext!.save()
        } catch let err {
            print("ERROR \(#file) => \(#function) => \(err.localizedDescription)")
        }
    }
    
    
}

extension Broadcast {
    
    static func getBroadcast() -> [Broadcast] {
        return fetcher.fetchResults().sorted { broadcast1, broadcast2 in
            return (broadcast1.time) > (broadcast2.time)
        }
    }
    
    static func getBroadcastById(_ id: Int) -> Broadcast? {
        let predicate = NSPredicate(format: "broadcast_id == %d", Int32(id))
        let result = fetcher.fetchResults(limit: 1, predicate: predicate)
        return result.first
    }
    
    public func getUsers() -> [Users] {
        return self.users?.map({ object in
            return object as! Users
        }) ?? []
    }
    
    public func getUserByUserID(_ user_id: String) -> Users? {
        let predicate = NSPredicate(format: "user_id == %@", user_id)
        let result = users?.filtered(using: predicate)
        return result?.first as? Users
    }
    
}
