package org.beetl.sql.core.range;

import org.beetl.sql.core.db.AbstractDBStyle;
import org.beetl.sql.core.db.DBAutoGeneratedSql;
import org.beetl.sql.core.db.PageParamKit;

import java.util.Map;

/**
 * oracle那样，使用RowNum辅助翻页的sql
 */
public class RowNumRange implements RangeSql {
    AbstractDBStyle dbStyle = null;
    public RowNumRange(AbstractDBStyle dbStyle){
        this.dbStyle = dbStyle;
    }
    @Override
    public String toRange(String jdbcSql, Object objOffset, Long limit) {
        Long offset = ((Number)objOffset).longValue();
        offset = PageParamKit.oracleOffset(dbStyle.offsetStartZero, offset);
        long pageEnd = PageParamKit.oraclePageEnd(offset, limit);
        int capacity = jdbcSql.length() + 133;
        StringBuilder builder = new StringBuilder(capacity);
        builder.append("SELECT * FROM ");
        builder.append(" ( ");
        builder.append(" SELECT beeltT.*, ROWNUM "+PAGE_FLAG+" ");
        builder.append(" FROM ( \n").append(jdbcSql).append("\n )  beeltT ");
        builder.append(" WHERE ROWNUM < ").append(pageEnd);
        builder.append(" ) ");
        builder.append("WHERE beetl_rn >= ").append(offset);

        return builder.toString();
    }

    @Override
    public String toTemplateRange(Class mapping,String template) {
        String pageSql = "SELECT * FROM "
                + " ( "
                + " SELECT beeltT.*, ROWNUM "+PAGE_FLAG+" "
                + " FROM ( \n" + template + dbStyle.getOrderBy() + "\n )  beeltT "
                + " WHERE ROWNUM <" + dbStyle.appendExpress(DBAutoGeneratedSql.PAGE_END )
                + ") "
                + "WHERE beetl_rn >= " + dbStyle.appendExpress(DBAutoGeneratedSql.OFFSET );
        return pageSql;
    }

    @Override
    public void addTemplateRangeParas(Map<String, Object> paras, Object objOffset, long size) {
        Long offset = (Long)objOffset;
        long s = offset + (dbStyle.offsetStartZero ? 1 : 0);
        paras.put(DBAutoGeneratedSql.OFFSET, s);
        paras.put(DBAutoGeneratedSql.PAGE_END, s + size);
    }
}
