//
//  StoryExtension.swift
//  WoWonder
//
//  Created by iMac on 25/09/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import Foundation

extension Story: CoreDataObject {
    
    convenience init(story: UserDataStory) {
        self.init(context: CoreDataManager.getInstance().context)
        self.id = story.id?.stringValue
        self.user_id = story.user_id?.stringValue
        self.title = story.title
        self.story_description = story.description
        self.posted = story.posted
        self.expire = story.expire
        self.thumbnail = story.thumbnail
        if let user = story.user_data {
            self.user_data = Users(user: user)
        }
        if let video = story.videos?.first {
            self.video = StoryVideo(storyVideo: video)
        }
        self.is_owner = story.is_owner ?? false
        self.reaction = Reactions(id: story.id?.stringValue ?? "", reaction: story.reaction)
        self.is_viewed = String(story.is_viewed ?? 0)
        self.time_text = story.time_text
        self.view_count = String(story.view_count ?? 0)
    }
    
    func save() {
        self.setValue(user_id, forKey: #keyPath(Story.user_id))
        self.setValue(title, forKey: #keyPath(Story.title))
        self.setValue(story_description, forKey: #keyPath(Story.story_description))
        self.setValue(posted, forKey: #keyPath(Story.posted))
        self.setValue(expire, forKey: #keyPath(Story.expire))
        self.setValue(thumbnail, forKey: #keyPath(Story.thumbnail))
        self.setValue(user_data, forKey: #keyPath(Story.user_data))
        self.setValue(video, forKey: #keyPath(Story.video))
        self.setValue(is_owner, forKey: #keyPath(Story.is_owner))
        self.setValue(reaction, forKey: #keyPath(Story.reaction))
        self.setValue(is_viewed, forKey: #keyPath(Story.is_viewed))
        self.setValue(time_text, forKey: #keyPath(Story.time_text))
        self.setValue(view_count, forKey: #keyPath(Story.view_count))
        
        do {
            try self.managedObjectContext!.save()
            
        } catch let err {
            print("ERROR \(#file) => \(#function) => \(err.localizedDescription)")
        }
    }
}
