package util.sqlparse.visitor.mongo.desensitization;

import bean.DataBase;
import java.util.ArrayList;
import java.util.Map;
import util.JdbcUtil;
import util.sqlparse.visitor.mongo.ApiParser;
import util.sqlparse.visitor.mongo.MongoParser;
import util.sqlparse.visitor.mongo.ParseResult;

public class FieldReplaceController {
   private final ParseResult result;
   private final Map params;
   private String replaceSchema;
   private String replaceTable;
   private String replaceColumn;
   private DataBase dataBase;

   public FieldReplaceController(ParseResult result, Map params, DataBase dataBase) {
      this.result = result;
      this.params = params;
      this.replaceSchema = (String)params.get("replaceSchema");
      this.replaceTable = (String)params.get("replaceTable");
      this.replaceColumn = (String)params.get("replaceColumn");
      this.dataBase = dataBase;
   }

   public void perform() {
      String schema = (String)this.params.get("schema");
      ArrayList<ParseResult.Column> list = new ArrayList();

      for(ParseResult.Column value : this.result.columns.values()) {
         boolean isHit = this.isHit(schema, value.collection, value.name);
         if (isHit) {
            list.add(value);
         }
      }

      String sql = (String)this.params.get("sql");
      if (list.size() > 0) {
         new ApiParser();
         FieldReplaceVisitor fieldReplaceVisitor = new FieldReplaceVisitor(this.params, list);
         MongoParser parserField = new MongoParser(fieldReplaceVisitor);
         parserField.parse(this.result.newMongoNode);
         ParseResult visitorResult = fieldReplaceVisitor.getResult();
         this.params.put("newSql", visitorResult.newMongoNode.toString());
         this.params.put("isMatched", "true");
      } else {
         this.params.put("newSql", sql);
         this.params.put("isMatched", "false");
      }

   }

   private boolean isHit(String schema, String tableName, String columnName) {
      return JdbcUtil.followRules(columnName, this.replaceColumn) && JdbcUtil.followRulesCaseSens(tableName, this.replaceTable) && JdbcUtil.followRulesCaseSens(schema, this.replaceSchema);
   }
}
