package com.chenyang.druid.sql.transform;

import com.chenyang.druid.DbType;
import com.chenyang.druid.sql.SQLUtils;
import com.chenyang.druid.sql.ast.SQLStatement;
import com.chenyang.druid.sql.parser.SQLParserFeature;
import com.chenyang.druid.sql.parser.SQLParserUtils;
import com.chenyang.druid.sql.parser.SQLType;
import com.chenyang.druid.sql.visitor.ParameterizedOutputVisitorUtils;
import com.chenyang.druid.util.FnvHash;
import com.chenyang.druid.util.StringUtils;

public class SQLUnifiedUtils {
   public static long unifyHash(String sql, DbType type) {
      String unifySQL = unifySQL(sql, DbType.mysql);
      return FnvHash.fnv1a_64_lower(unifySQL);
   }

   public static String unifySQL(String sql, DbType type) {
      if (StringUtils.isEmpty(sql)) {
         throw new IllegalArgumentException("sql is empty.");
      } else {
         SQLType sqlType = SQLParserUtils.getSQLType(sql, DbType.mysql);
         String parameterizeSQL = null;
         switch (sqlType) {
            case INSERT:
            case UPDATE:
            case SELECT:
            case DELETE:
               parameterizeSQL = ParameterizedOutputVisitorUtils.parameterize(sql, DbType.mysql);
               SQLStatement stmt = SQLUtils.parseSingleStatement(parameterizeSQL, DbType.mysql, SQLParserFeature.EnableSQLBinaryOpExprGroup);
               stmt.accept(new SQLUnifiedVisitor());
               return SQLUtils.toMySqlString(stmt);
            default:
               return ParameterizedOutputVisitorUtils.parameterize(sql, DbType.mysql);
         }
      }
   }
}
