package util.sqlparse.visitor.mongo;

import java.util.HashMap;
import java.util.Map;
import org.bson.BsonDocument;
import org.bson.BsonValue;

public class BsonObjectNode extends BsonNode {
   private BsonDocument value;
   private Map<String, MongoNode> children = new HashMap();

   public BsonObjectNode() {
   }

   public BsonDocument getValue() {
      return this.value;
   }

   public void setValue(BsonDocument value) {
      this.value = value;
   }

   public BsonObjectNode(String name, BsonDocument doc) {
      this.value = doc;
      this.name = name;

      for(Map.Entry<String, BsonValue> entry : doc.entrySet()) {
         BsonValue value = (BsonValue)entry.getValue();
         String key = (String)entry.getKey();
         MongoNode node = BsonNode.create(key, value);
         node.setParent(this);
         this.children.put(entry.getKey(), node);
      }

   }

   public Object value() {
      return this.value;
   }

   public void value(Object raw, Object... other) {
      if (raw instanceof BsonDocument) {
         this.value = (BsonDocument)raw;
      }

   }

   public <T extends MongoNode> T get(String key) {
      MongoNode mongoNode = (MongoNode)this.children.get(key);
      return (T)mongoNode;
   }

   public void put(String key, MongoNode node) {
      this.children.put(key, node);
      this.value.put(key, node.data());
      node.setParent(this);
   }

   public void put(String key, BsonValue value) {
      MongoNode node = BsonNode.create(key, value);
      node.setParent(this);
      this.children.put(key, node);
      this.value.put(key, node.data());
      node.setParent(this);
   }

   public void remove(String key) {
      this.children.remove(key);
      this.value.remove(key);
   }

   public boolean contains(String key) {
      return this.children.containsKey(key);
   }

   public Map<String, MongoNode> children() {
      return this.children;
   }

   public void add(String name, MongoNode node) {
      this.children.put(name, node);
   }

   public void delete(String name) {
      this.children.remove(name);
      this.value.remove(name);
   }

   public int size() {
      return this.children.size();
   }

   public BsonValue data() {
      return this.value;
   }

   public BsonNodeType type() {
      return BsonNodeType.Object;
   }

   public BsonObjectNode clone() {
      BsonDocument value = this.value.clone();
      return new BsonObjectNode(null, value);
   }
}
