//
//  GroupChatsExtension.swift
//  WoWonder
//
//  Created by iMac on 07/08/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import Foundation

extension GroupChat: CoreDataObject {
    
    private static var fetcher: CoreDataFetcher<GroupChat> {
        get {
            return CoreDataFetcher<GroupChat>()
        }
    }
    
    convenience init(group: GroupData) {
        self.init(context: CoreDataManager.getInstance().context)
        self.group_id = group.group_id
        self.user_id = group.user_id
        self.group_name = group.group_name
        self.avatar = group.avatar
        self.time = group.time
        if let user = group.user_data {
            self.user_data = Users(user: user)
        }
        self.owner = group.owner ?? false
        if let lastMessage = group.last_message?.last_message {
            if let message = Messages.getMessageByID(lastMessage.id ?? "") {
                // message.updateMessage(message: lastMessage)
                self.last_message = message
            } else {
                self.last_message = Messages(chat_id: group.chat_id ?? "", message: lastMessage)
            }
        }
        self.chat_time = group.chat_time
        self.chat_id = group.chat_id
        if let mute = group.mute {
            self.mute = Mute(mute: mute)
        }
        for part in group.parts ?? [] {
            self.addToParts(Users(user: part))
        }
    }
    
    func updateGroupChat(_ group: GroupData) {
        self.group_id = group.group_id
        self.user_id = group.user_id
        self.group_name = group.group_name
        self.avatar = group.avatar
        self.time = group.time
        if let user = group.user_data {
            self.user_data = Users(user: user)
        }
        self.owner = group.owner ?? false
        if let lastMessage = group.last_message?.last_message {
            if let message = Messages.getMessageByID(lastMessage.id ?? "") {
                // message.updateMessage(message: lastMessage)
                self.last_message = message
            } else {
                self.last_message = Messages(chat_id: group.chat_id ?? "", message: lastMessage)
            }
        }
        self.chat_time = group.chat_time
        self.chat_id = group.chat_id
        if let mute = group.mute {
            self.mute = Mute(mute: mute)
        }
        
        for part in self.getParts() {
            self.removeFromParts(part)
        }
        
        for part in group.parts ?? [] {
            self.addToParts(Users(user: part))
        }
        self.save()
    }
    
    func save() {
        self.setValue(group_id, forKey: #keyPath(GroupChat.group_id))
        self.setValue(user_id, forKey: #keyPath(GroupChat.user_id))
        self.setValue(group_name, forKey: #keyPath(GroupChat.group_name))
        self.setValue(avatar, forKey: #keyPath(GroupChat.avatar))
        self.setValue(time, forKey: #keyPath(GroupChat.time))
        self.setValue(user_data, forKey: #keyPath(GroupChat.user_data))
        self.setValue(owner, forKey: #keyPath(GroupChat.owner))
        self.setValue(last_message, forKey: #keyPath(GroupChat.last_message))
        self.setValue(chat_time, forKey: #keyPath(GroupChat.chat_time))
        self.setValue(chat_id, forKey: #keyPath(GroupChat.chat_id))
        self.setValue(mute, forKey: #keyPath(GroupChat.mute))
        do {
            try self.managedObjectContext!.save()
        } catch let err {
            print("ERROR \(#file) => \(#function) => \(err.localizedDescription)")
        }
    }
    
}

extension GroupChat {    
    
    static func getChats() -> [GroupChat] {
        return fetcher.fetchResults().sorted { chat1, chat2 in
            return (chat1.chat_time ?? "") > (chat2.chat_time ?? "")
        }
    }
    
    static func getGroupChatByGroupID(_ group_id: String) -> GroupChat? {
        let predicate = NSPredicate(format: "group_id == %@", group_id)
        let result = fetcher.fetchResults(limit: 1, predicate: predicate)
        return result.first
    }
    
    public func getParts() -> [Users] {
        return self.parts?.map({ object in
            return object as! Users
        }) ?? []
    }
    
    public func getPartByUserID(_ user_id: String) -> Users? {
        let predicate = NSPredicate(format: "user_id == %@", user_id)
        let result = parts?.filtered(using: predicate)
        return result?.first as? Users
    }
    
}
