import Foundation

public class SynchronizedArray<V> {
    private var array: [V] = []
    private let queue = DispatchQueue(label: "com.castlabs.Prestoplay.SynchronizedArray", attributes: .concurrent)

    func append(_ value: V) {
        queue.async(flags: .barrier) { [weak self] in
            self?.array.append(value)
        }
    }

    func remove(at index: Int) -> V? {
        var result: V?
        queue.sync(flags: .barrier) { [weak self] in
            guard let self = self, index < self.array.count else { return }
            result = self.array.remove(at: index)
        }
        return result
    }

    func get(at index: Int) -> V? {
        var result: V?
        queue.sync { [weak self] in
            guard let self = self, index < self.array.count else { return }
            result = self.array[index]
        }
        return result
    }

    var count: Int {
        var result = 0
        queue.sync {
            result = array.count
        }
        return result
    }
}
