//
//  UsersExtension.swift
//  WoWonder
//
//  Created by Mohammed Hamad on 02/08/2022.
//  Copyright © 2022 ScriptSun. All rights reserved.
//

import Foundation
import CoreData
import UIKit

extension Users: CoreDataObject {
    
    private static var fetcher: CoreDataFetcher<Users> {
        get {
            return CoreDataFetcher<Users>()
        }
    }
    
    convenience init(user: UserData) {
        self.init(context: CoreDataManager.getInstance().context)
        self.about = user.about
        self.gender = user.gender
        self.password = user.password
        self.message_count = user.message_count
        self.lng = user.lng
        self.lat = user.lat
        self.last_seen_status = user.lastseen_status
        self.show_last_seen = user.showlastseen
        self.ip_address = user.ip_address
        self.email = user.email
        self.cover_url = user.cover
        self.chat_type = user.chat_type
        self.chat_time = user.chat_time?.stringValue
        self.name = user.name
        self.last_seen = user.lastseen
        self.last_name = user.last_name
        self.first_name = user.first_name
        self.username = user.username
        self.avatar_url = user.avatar
        self.user_id = user.user_id
        self.is_blocked = user.is_blocked ?? false
        self.last_message_id = user.last_message?.id
        self.my_id = Users.getMaxID() + 1
        self.chat_id = user.chat_id?.stringValue ?? ""
        if let lastMessage = user.last_message {
            if let message = Messages.getMessageByID(lastMessage.id ?? "") {
                message.updateMessage(message: lastMessage)
                self.last_message = message
            } else {
                self.last_message = Messages(chat_id: user.chat_id?.stringValue ?? "", message: lastMessage)
            }
        }
        self.user_mute = Mute(mute: user.mute)
        self.is_reported = user.is_reported ?? false
        self.message_privacy = user.message_privacy
        self.follow_privacy = user.follow_privacy
        self.birth_privacy = user.birth_privacy
        self.is_following = String(user.is_following ?? 0)
        self.is_following_me = String(user.is_following_me ?? 0)
//        self.addToMututal_friends(NSSet(
//            array: user._mutualFriendsData.map({
//                return MutualFriends(userID: user._userID, friendID: $0)
//            })
//        ))
        
//        self.addToFollowings(NSSet(
//            array: user._followingData.map({
//                return FollowingsData(userID: user._userID, following_user_id: $0)
//            })
//        ))
        
//        self.addToFollowers(NSSet(
//            array: user._followersData.map({
//                return FollowersData(userID: user._userID, follower_user_id: $0)
//            })
//        ))
    }
    
    func updateUser(user: UserData) {
        self.about = user.about
        self.gender = user.gender
        self.password = user.password
        self.message_count = user.message_count
        self.lng = user.lng
        self.lat = user.lat
        self.last_seen_status = user.lastseen_status
        self.show_last_seen = user.showlastseen
        self.ip_address = user.ip_address
        self.email = user.email
        self.cover_url = user.cover
        self.chat_type = user.chat_type
        self.chat_time = user.chat_time?.stringValue
        self.name = user.name
        self.last_seen = user.lastseen
        self.last_name = user.last_name
        self.first_name = user.first_name
        self.username = user.username
        self.avatar_url = user.avatar
        self.user_id = user.user_id
        self.is_blocked = user.is_blocked ?? false
        self.last_message_id = user.last_message?.id
        self.my_id = Users.getMaxID() + 1
        self.chat_id = user.chat_id?.stringValue ?? ""
        if let lastMessage = user.last_message {
            if let message = Messages.getMessageByID(lastMessage.id ?? "") {
                message.updateMessage(message: lastMessage)
                self.last_message = message
            } else {
                self.last_message = Messages(chat_id: user.chat_id?.stringValue ?? "", message: lastMessage)
            }
        }
        self.user_mute = Mute(mute: user.mute)
        self.is_reported = user.is_reported ?? false
        self.message_privacy = user.message_privacy
        self.follow_privacy = user.follow_privacy
        self.birth_privacy = user.birth_privacy
        self.is_following = String(user.is_following ?? 0)
        self.is_following_me = String(user.is_following_me ?? 0)
        self.save()
    }
    
    func save() {
        self.setValue(about, forKey: #keyPath(Users.about))
        self.setValue(gender, forKey: #keyPath(Users.gender))
        self.setValue(message_count, forKey: #keyPath(Users.message_count))
        self.setValue(lng, forKey: #keyPath(Users.lng))
        self.setValue(lat, forKey: #keyPath(Users.lat))
        self.setValue(last_seen_status, forKey: #keyPath(Users.last_seen_status))
        self.setValue(ip_address, forKey: #keyPath(Users.ip_address))
        self.setValue(email, forKey: #keyPath(Users.email))
        self.setValue(password, forKey: #keyPath(Users.password))
        self.setValue(cover_url, forKey: #keyPath(Users.cover_url))
        self.setValue(chat_type, forKey: #keyPath(Users.chat_type))
        self.setValue(chat_time, forKey: #keyPath(Users.chat_time))
        self.setValue(name, forKey: #keyPath(Users.name))
        self.setValue(last_seen, forKey: #keyPath(Users.last_seen))
        self.setValue(last_name, forKey: #keyPath(Users.last_name))
        self.setValue(first_name, forKey: #keyPath(Users.first_name))
        self.setValue(username, forKey: #keyPath(Users.username))
        self.setValue(avatar_url, forKey: #keyPath(Users.avatar_url))
        self.setValue(user_id, forKey: #keyPath(Users.user_id))
        self.setValue(is_blocked, forKey: #keyPath(Users.is_blocked))
        self.setValue(my_id, forKey: #keyPath(Users.my_id))
        self.setValue(chat_id, forKey: #keyPath(Users.chat_id))
        
        do {
            try self.managedObjectContext!.save()
            
        } catch let err {
            print("ERROR \(#file) => \(#function) => \(err.localizedDescription)")
        }
    }
    
    static func getUserByID(_ userId: String) -> Users? {
        let predicate = NSPredicate(format: "%K == %@", #keyPath(Users.user_id), userId)
        let result = fetcher.fetchResults(limit: 1,
                                          predicate: predicate)
        return result.first
    }
    
    static func getMaxID() -> Int32 {
        let sortDescriptor = NSSortDescriptor(key: #keyPath(Users.my_id), ascending: false)
        let results = fetcher.fetchResults(limit: 1, sortDescriptors: [sortDescriptor])
        return results.first?.my_id ?? 0
    }
}
