//
//  GameCenterHelper.swift
//  GoldWars
//
//  Created by Jakob Haag on 02.05.20.
//  Copyright © 2020 SP2. All rights reserved.
//

import GameKit

final class GameCenterHelper: NSObject {
    typealias CompletionBlock = (Error?) -> Void
    
    static let helper = GameCenterHelper()

    var viewController: UIViewController?
    
    static var isAuthenticated: Bool {
      return GKLocalPlayer.local.isAuthenticated
    }
    
    override init() {
        super.init()
      
        GKLocalPlayer.local.authenticateHandler = { gcAuthVC, error in
            NotificationCenter.default
            .post(name: .authenticationChanged, object: GKLocalPlayer.local.isAuthenticated)

            if GKLocalPlayer.local.isAuthenticated {
                print("Authenticated to Game Center!")
            } else if let vc = gcAuthVC {
                self.viewController?.present(vc, animated: true)
            }
            else {
                print("Error authentication to GameCenter: " +
                    "\(error?.localizedDescription ?? "none")")
            }
        }
    }
}

extension Notification.Name {
    static let presentGame = Notification.Name(rawValue: "presentGame")
    static let authenticationChanged = Notification.Name(rawValue: "authenticationChanged")
}
