package util.sqlparse.visitor.mongo.desensitization;

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

public class Desensitization {
   public Map parseColumn(Map params) {
      return this.parseData(params);
   }

   public Map parseData(Map params) {
      String sql = (String)params.get("sql");
      ApiParser parser = new ApiParser();
      DataBase dataBase = null;
      params.put("newSql", sql);
      String url = (String)params.get("url");
      String ipPort = url.split("/")[2];

      for(DataBase base : JdbcUtil.dataBaseList) {
         if (base.getIp_port().equalsIgnoreCase(ipPort)) {
            dataBase = base;
         }
      }

      String schema = (String)params.get("schema");
      ParseResult result = parser.parse(sql, dataBase, schema);
      if ("select".equals(result.sqlType)) {
         FieldReplaceController controller = new FieldReplaceController(result, params, dataBase);
         controller.perform();
      }

      return params;
   }

   public Map parseTable(Map params) {
      String sql = (String)params.get("sql");
      ApiParser apiParser = new ApiParser();
      MongoNode node = apiParser.convert(sql);
      TableReplaceVisitor visitor = new TableReplaceVisitor(params);
      MongoParser parser = new MongoParser(visitor);
      parser.parse(node);
      ParseResult visitorResult = visitor.getResult();
      params.put("isMatched", Boolean.toString(visitorResult.isMatched));
      if (visitorResult.isMatched) {
         params.put("newSql", visitorResult.newMongoNode.toString());
      } else {
         params.put("newSql", sql);
      }

      return params;
   }

   public Map parseRowVisit(Map params) {
      ParseResult result = this.getSqlResult(params);
      RowVisitController controller = new RowVisitController(result, params);
      controller.perform();
      return params;
   }

   private ParseResult getSqlResult(Map params) {
      String sql = (String)params.get("sql");
      ApiParser parser = new ApiParser();
      DataBase dataBase = null;
      params.put("newSql", sql);
      String url = (String)params.get("url");
      String ipPort = url.split("/")[2];

      for(DataBase base : JdbcUtil.dataBaseList) {
         if (base.getIp_port().equalsIgnoreCase(ipPort)) {
            dataBase = base;
         }
      }

      String schema = (String)params.get("schema");
      ParseResult result = parser.parse(sql, dataBase, schema);
      return result;
   }
}
