//
//  Console+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
import UIKit

@objc(Console)
public class Console: NSManagedObject, Identifiable {
    public static func compareConsolesByNewestGame(consoleA : Console, consoleB : Console) -> Bool {
        guard let newestGameConsoleA = (consoleA.games!.allObjects as! [Game]).max(by:{
            Game.compareByCreationDate(gameA: $0, gameB: $1)
        }) else { return false }
        guard let newestGameConsoleB = (consoleB.games!.allObjects as! [Game]).max(by:{
            Game.compareByCreationDate(gameA: $0, gameB: $1)
        }) else { return false }
        
        guard let gameACreated = newestGameConsoleA.createdAt else { return true }
        guard let gameBCreated = newestGameConsoleB.createdAt else { return false }
        
        return gameACreated > gameBCreated
    }
    
    public var id : NSManagedObjectID {
        get {
            return self.objectID
        }
    }
    
    // Defining default values during creation
    public override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
        super.init(entity: entity, insertInto: context)
        self.uuid = UUID()
        self.releaseDate = Date()
    }
}

extension Console : Encodable {
    
    enum CodingKeys: String, CodingKey {
        case uuid
        case name
        case shortName
        case manufacturer
        case accessories
        case games
        case logo_icloud_path
        case releaseDate
    }
    
    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(shortName ?? "", forKey: .shortName)
        try container.encode(manufacturer ?? "", forKey: .manufacturer)
        try container.encode(logo_icloud_path ?? "", forKey: .logo_icloud_path)
        print("Encode releaseDate: \(releaseDate)")
        try container.encode(releaseDate, forKey: .releaseDate)
        var accessoryList : [String] = []
        for accessory in accessories! {
            if let accessory = accessory as? Accessory {
                accessoryList.append(accessory.uuid.uuidString)
            }
        }
        try container.encode(accessoryList, forKey: .accessories)
        
        var gamesList : [String] = []
        for game in games! {
            if let game = game as? Game {
                gamesList.append(game.uuid.uuidString)
            }
        }
        try container.encode(gamesList, forKey: .games)
    }
}
