package com.alibaba.druid.sql.dialect.es.test;

import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.es.ast.EsLexer;
import com.alibaba.druid.sql.dialect.es.ast.EsParser;
import com.alibaba.druid.sql.dialect.es.visitor.ESOutputVisitor;
import com.alibaba.druid.sql.dialect.es.visitor.Printer;
import com.alibaba.druid.sql.visitor.SchemaStatVisitor;
import com.alibaba.druid.stat.TableStat;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import util.JdbcUtil;
import util.sqlparse.visitor.es.visitor.ElasticSchemaVisitor;

public class ParseTest {
   public static void main(String[] args) {
      test1();
   }

   static void test2() {
      String content = "{\n      \"ip_port\": \"192.168.2.229:9200\",\n      \"url\": \"http://192.168.2.229:9200\",\n      \"username\": \"test1\",\n      \"password\": \"123456\",\n      \"dbType\": \"es\",\n      \"excludeSchema\": []\n    }";
      JdbcUtil.initData(content);

      try {
         Thread.sleep(2000L);
      } catch (InterruptedException e) {
         e.printStackTrace();
      }

      String query = "GET /emp/_search\n{}\n";
      String dbType = "es";
      List<SQLStatement> statements = SQLUtils.parseStatements(query, "es");
      SQLStatement st = (SQLStatement)statements.get(0);
      SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(DbType.of(dbType));
      ElasticSchemaVisitor esVisitor = (ElasticSchemaVisitor)visitor;
      HashMap params = new HashMap();
      params.put("sql", query);
      params.put("url", "http://192.168.2.229:9200");
      params.put("dbType", "es");
      esVisitor.setParams(params);
      st.accept(visitor);
      Map<TableStat.Name, TableStat> tables = visitor.getTables();
      Collection<TableStat.Column> columns = visitor.getColumns();
      System.out.println("over");
   }

   static void test1() {
      String query = "GET /_search\n{\n  \"query\": {\n    \"span_near\": {\n      \"clauses\": [\n        { \"span_term\": { \"field\": \"value1\" } },\n        { \"span_term\": { \"field\": \"value2\" } },\n        { \"span_term\": { \"field\": \"value3\" } }\n      ],\n      \"slop\": 12,\n      \"in_order\": false\n    }\n  }\n}\n";
      CharStream stream = new ANTLRInputStream(query);
      EsLexer lexer = new EsLexer(stream);
      CommonTokenStream tokenStream = new CommonTokenStream(lexer);
      EsParser parser = new EsParser(tokenStream);
      EsParser.StatementContext context = parser.statement();
      ESOutputVisitor visitor = new ESOutputVisitor();
      Printer printer = visitor.visit(context);
      System.out.println(printer);
   }
}
