//
//  Weak.swift
//  Tusker
//
//  Created by Shadowfacts on 3/25/20.
//  Copyright © 2020 Shadowfacts. All rights reserved.
//

import Foundation

class WeakHolder<T: AnyObject> {
    weak var object: T?
    
    init(_ object: T?) {
        self.object = object
    }
}

struct WeakArray<Element: AnyObject>: MutableCollection, RangeReplaceableCollection {
    private var array: [WeakHolder<Element>]
    
    var startIndex: Int { array.startIndex }
    var endIndex: Int { array.endIndex }
    
    init() {
        array = []
    }
    
    init(_ elements: [Element]) {
        array = elements.map { WeakHolder($0) }
    }
    
    init(_ elements: [Element?]) {
        array = elements.map { WeakHolder($0) }
    }
    
    subscript(position: Int) -> Element? {
        get {
            array[position].object
        }
        set(newValue) {
            array[position] = WeakHolder(newValue)
        }
    }
    
    func index(after i: Int) -> Int {
        return array.index(after: i)
    }
    
    mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) where C : Collection, Self.Element == C.Element {
        array.replaceSubrange(subrange, with: newElements.map { WeakHolder($0) })
    }
}
