package util.sqlparse.visitor.mongo;

import java.util.List;
import java.util.Map;
import org.bson.BsonString;
import org.bson.BsonValue;
import util.sqlparse.visitor.common.bean.FieldInfo;
import util.sqlparse.visitor.common.bean.ValueInfo;
import util.sqlparse.visitor.common.memo.ValueMemo;

public class ValueReplacer {
   private Map<String, String> replace;
   private List<Map> whereList;

   public ValueReplacer(Map<String, String> replace) {
      this.replace = replace;
   }

   public ValueReplacer(List<Map> whereList) {
      this.whereList = whereList;
   }

   public void replaceValuesWithList(List<ValueInfo> values) {
      if (values != null && values.size() != 0) {
         if (this.whereList != null && this.whereList.size() != 0) {
            for(int i = 0; i < this.whereList.size(); ++i) {
               ValueInfo value = (ValueInfo)values.get(i);
               Map valueMap = (Map)this.whereList.get(i);
               String newVal = (String)valueMap.get("columnValue");
               if (value.getFields() != null && value.getFields().size() > 0 && ((FieldInfo)value.getFields().get(0)).getName() != null) {
                  this.replaceValue(value, newVal, ((FieldInfo)value.getFields().get(0)).getName());
               }
            }

         }
      }
   }

   private void replaceValue(ValueMemo value, String newVal, String key) {
      if (value != null && value.field != null) {
         if (value != null && value.refMongo instanceof BsonBasicNode) {
            BsonBasicNode refMongo = (BsonBasicNode)value.refMongo;
            if (refMongo.getValue() != null && refMongo.getValue().isString()) {
               BsonString newBsonValue = new BsonString(newVal);
               if (value.nodeMongo instanceof BsonArrayNode) {
                  if (value.refMongo instanceof BsonBasicNode) {
                     BsonBasicNode bsonBasicNode = new BsonBasicNode();
                     bsonBasicNode.setValue(newBsonValue);
                     BsonArrayNode arrayNode = (BsonArrayNode)value.nodeMongo;

                     for(int i = 0; i < arrayNode.children.size(); ++i) {
                        MongoNode mongoNode = (MongoNode)arrayNode.children.get(i);
                        if (value.refMongo == mongoNode) {
                           arrayNode.set(i, bsonBasicNode);
                        }
                     }
                  }
               } else if (value.operator.startsWith("$")) {
                  ((BsonObjectNode)value.nodeMongo).put(value.operator, (BsonValue)newBsonValue);
               } else if (value.nodeMongo instanceof BsonObjectNode) {
                  ((BsonObjectNode)value.nodeMongo).put(key, (BsonValue)newBsonValue);
               }
            }
         }

      }
   }
}
