//
//  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 func addGameSeries(by objectIDStringified : String) {
        if let url = URL(string: objectIDStringified) {
            let persistentStoreCoordinator = CDManager.shared.persistentContainer.persistentStoreCoordinator

            if let objectID = persistentStoreCoordinator.managedObjectID(forURIRepresentation: url) {
                if let gameSeries = CDManager.shared.viewContext.object(with: objectID) as? GameSeries {
                    self.series = gameSeries
                }
            }
        }
    }
    
    public static func compareByCreationDate(gameA : Game, gameB : Game) -> Bool {
        guard let gameACreated = gameA.createdAt else { return true }
        guard let gameBCreated = gameB.createdAt else { return false }
        
        return gameACreated < gameBCreated
    }
    
    public var id : NSManagedObjectID {
        get {
            return self.objectID
        }
    }
    
    @objc
    private override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
        super.init(entity: entity, insertInto: context)
        
        if self.createdAt == .none {
            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 inWishlist
        case console
        case gameSeries
        case cover_icloud_path
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        print("UUID: \(self.uuid)")
        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(publisher ?? "", forKey: .publisher)
        try container.encode(isFinished, forKey: .isFinished)
        try container.encode(inWishlist, forKey: .inWishlist)
        try container.encode(cover_icloud_path ?? "", forKey: .cover_icloud_path)
        
        let consoleUUID : String = console?.uuid.uuidString ?? ""
        let gameSeriesUUID : String = series?.uuid.uuidString ?? ""
        try container.encode(consoleUUID, forKey: .console)
        try container.encode(gameSeriesUUID, forKey: .gameSeries)
    }
}
