//
//  MulticastDelegate.swift
//  OneWeather
//
//  Created by Demid Merzlyakov on 11.01.2021.
//  Copyright © 2021 OneLouder, Inc. All rights reserved.
//

import Foundation

public class MulticastDelegate <T> {
    public init() {}
    private let delegates: NSHashTable<AnyObject> = NSHashTable.weakObjects()
    
    public func add(delegate: T) {
        if delegates.contains(delegate as AnyObject) {
            return
        }
        
        delegates.add(delegate as AnyObject)
    }
    
    public func remove(delegate: T) {
        for oneDelegate in delegates.allObjects.reversed() {
            if oneDelegate === delegate as AnyObject {
                delegates.remove(oneDelegate)
            }
        }
    }
    
    public func invoke(invocation: (T) -> ()) {
        for delegate in delegates.allObjects.reversed() {
            invocation(delegate as! T)
        }
    }
}

public func += <T: AnyObject> (left: MulticastDelegate<T>, right: T) {
    left.add(delegate: right)
}

public func -= <T: AnyObject> (left: MulticastDelegate<T>, right: T) {
    left.remove(delegate: right)
}
