//
// © 2017-2020 Qualcomm Technologies, Inc. and/or its subsidiaries. All rights reserved.
//

import UIKit
import CocoaLumberjack

protocol UIViewControllerDependencies {
    func injectDependencies(preferences: Preferences, playerController: PlayerControllerProtocol)
}

extension UIViewController {
    private struct AssociatedKeys {
        static var preferences : Preferences? = nil
        static var playerController: PlayerControllerProtocol? = nil
    }

    private(set) var preferences : Preferences {
        get {
            guard let p = objc_getAssociatedObject(self, &AssociatedKeys.preferences) as? Preferences else {
                fatalError("Preferences not injected into \(self)")
            }
            return p
        }
        set(newValue) {
            objc_setAssociatedObject(self, &AssociatedKeys.preferences, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    private(set) var playerController : PlayerControllerProtocol {
        get {
            guard let apc = objc_getAssociatedObject(self, &AssociatedKeys.playerController) as? PlayerControllerProtocol else {
                fatalError("PlayerController not injected into \(self)")
            }
            return apc
        }
        set(newValue) {
            objc_setAssociatedObject(self, &AssociatedKeys.playerController, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    func injectDependencies(preferences: Preferences, playerController: PlayerControllerProtocol) {
        self.preferences = preferences
        self.playerController = playerController
        for child in children {
            child.injectDependencies(preferences: preferences, playerController: playerController)
        }
    }
}
