package com.chenyang.druid.sql.dialect.clickhouse.parser;

import com.chenyang.druid.sql.ast.SQLExpr;
import com.chenyang.druid.sql.ast.SQLOrderBy;
import com.chenyang.druid.sql.ast.statement.SQLAssignItem;
import com.chenyang.druid.sql.ast.statement.SQLCreateTableStatement;
import com.chenyang.druid.sql.dialect.clickhouse.ast.ClickhouseCreateTableStatement;
import com.chenyang.druid.sql.parser.SQLCreateTableParser;
import com.chenyang.druid.sql.parser.SQLExprParser;
import com.chenyang.druid.sql.parser.Token;
import com.chenyang.druid.util.FnvHash;

public class ClickhouseCreateTableParser extends SQLCreateTableParser {
   public ClickhouseCreateTableParser(SQLExprParser exprParser) {
      super(exprParser);
   }

   protected SQLCreateTableStatement newCreateStatement() {
      return new ClickhouseCreateTableStatement();
   }

   protected void parseCreateTableRest(SQLCreateTableStatement stmt) {
      ClickhouseCreateTableStatement ckStmt = (ClickhouseCreateTableStatement)stmt;
      if (this.lexer.identifierEquals(FnvHash.Constants.ENGINE)) {
         this.lexer.nextToken();
         if (this.lexer.token() == Token.EQ) {
            this.lexer.nextToken();
         }

         stmt.setEngine(this.exprParser.expr());
      }

      if (this.lexer.identifierEquals("PARTITION")) {
         this.lexer.nextToken();
         this.accept(Token.BY);
         SQLExpr expr = this.exprParser.expr();
         ckStmt.setPartitionBy(expr);
      }

      if (this.lexer.token() == Token.ORDER) {
         SQLOrderBy orderBy = this.exprParser.parseOrderBy();
         ckStmt.setOrderBy(orderBy);
      }

      if (this.lexer.identifierEquals("SAMPLE")) {
         this.lexer.nextToken();
         this.accept(Token.BY);
         SQLExpr expr = this.exprParser.expr();
         ckStmt.setSampleBy(expr);
      }

      if (this.lexer.identifierEquals("SETTINGS")) {
         this.lexer.nextToken();

         while(true) {
            SQLAssignItem item = this.exprParser.parseAssignItem();
            item.setParent(ckStmt);
            ckStmt.getSettings().add(item);
            if (this.lexer.token() != Token.COMMA) {
               break;
            }

            this.lexer.nextToken();
         }
      }

   }
}
