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

import Foundation
import CoreData
import UIKit

extension Reactions: CoreDataObject {
    
    convenience init(id: String, reaction: ReactionModel?) {
        self.init(context: CoreDataManager.getInstance().context)
        self.id = id
        if let the1 = reaction?.the1 {
            self.the1 = String(the1)
        } else {
            self.the1 = nil
        }
        if let the2 = reaction?.the2 {
            self.the2 = String(the2)
        } else {
            self.the2 = nil
        }
        if let the3 = reaction?.the3 {
            self.the3 = String(the3)
        } else {
            self.the3 = nil
        }
        if let the4 = reaction?.the4 {
            self.the4 = String(the4)
        } else {
            self.the4 = nil
        }
        if let the5 = reaction?.the5 {
            self.the5 = String(the5)
        } else {
            self.the5 = nil
        }
        if let the6 = reaction?.the6 {
            self.the6 = String(the6)
        } else {
            self.the6 = nil
        }
        self.is_reacted = reaction?.is_reacted ?? false
        self.type = reaction?.type
        self.count = Int16(exactly: reaction?.count ?? 0) ?? 0
    }
    
    func save() {
        self.setValue(is_reacted, forKey: #keyPath(Reactions.is_reacted))
        self.setValue(type, forKey: #keyPath(Reactions.type))
        self.setValue(count, forKey: #keyPath(Reactions.count))
        
        do {
            try self.managedObjectContext!.save()
            
        } catch let err {
            print("ERROR \(#file) => \(#function) => \(err.localizedDescription)")
        }
    }
    
}
