/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 */

class ConcurrentHashMap<V: Hashable,T>: Collection {
  
  private var dictionary: [V: T]
  private let concurrentQueue = DispatchQueue(label: "Concurrent Queue", attributes: .concurrent)
  
  var startIndex: Dictionary<V, T>.Index {
    self.concurrentQueue.sync {
      return self.dictionary.startIndex
    }
  }
  
  var endIndex: Dictionary<V, T>.Index {
    self.concurrentQueue.sync {
      return self.dictionary.endIndex
    }
  }
  
  init(dict: [V: T] = [V: T]()) {
    self.dictionary = dict
  }
  
  func index(after i: Dictionary<V, T>.Index) -> Dictionary<V, T>.Index {
    return self.dictionary.index(after: i)
  }
  
  subscript(key: V) -> T? {
    get {
      self.concurrentQueue.sync {
        return self.dictionary[key]
      }
    }
    set(newValue) {
      self.concurrentQueue.async(flags: .barrier) {[weak self] in
        self?.dictionary[key] = newValue
      }
    }
  }
  
  subscript(index: Dictionary<V, T>.Index) -> Dictionary<V, T>.Element {
    self.concurrentQueue.sync {
      return self.dictionary[index]
    }
  }
  
  func removeValue(forKey key: V) {
    self.concurrentQueue.async(flags: .barrier) { [weak self] in
      self?.dictionary.removeValue(forKey: key)
    }
  }
  
}
