//
//  Game+CoreDataClass.swift
//  Zockerhoehle
//
//  Created by Julian-Steffen Müller on 06.07.19.
//  Copyright © 2019 Julian-Steffen Müller. All rights reserved.
//
//

import Foundation
import CoreData
import SwiftUI

@objc(Game)
public class Game: NSManagedObject, Identifiable {
   
    public static func compareByCreationDate(gameA : Game, gameB : Game) -> Bool {
        return gameA.createdAt < gameB.createdAt
    }
    
    @objc
    private override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
        super.init(entity: entity, insertInto: context)
        
        self.createdAt = Date()
        self.uuid = UUID()
        print("Set UUID to \(self.uuid)")
    }
}

extension Game : Encodable {
    enum CodingKeys: String, CodingKey {
        case uuid
        case name
        case notes
        case isDigital
        case lentTo
        case createdAt
        case publisher
        case isFinished
        case finishedDate
        case inWishlist
        case console
        case cover_icloud_path
        case pickupDescription
        case playtime_h
        case playtime_min
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(uuid, forKey: .uuid)
        try container.encode(name, forKey: .name)
        try container.encode(notes ?? "", forKey: .notes)
        try container.encode(isDigital, forKey: .isDigital)
        try container.encode(lentTo ?? "", forKey: .lentTo)
        try container.encode(createdAt.formattedInTimeZone(), forKey: .createdAt)
        try container.encode(pickupDescription ?? "", forKey: .pickupDescription)
        try container.encode(publisher ?? "", forKey: .publisher)
        try container.encode(isFinished, forKey: .isFinished)
        try container.encode(finishedDate, forKey: .finishedDate)
        try container.encode(inWishlist, forKey: .inWishlist)
        try container.encode(cover_icloud_path ?? "", forKey: .cover_icloud_path)
        try container.encode(playtime_h, forKey: .playtime_h)
        try container.encode(playtime_min, forKey: .playtime_min)
        
        let consoleUUID : String = console?.uuid.uuidString ?? ""
        try container.encode(consoleUUID, forKey: .console)
    }
}
