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;

/**
 * mysql那样支持offset limit
 */
public class OffsetLimitRange implements RangeSql {
    AbstractDBStyle sqlStyle = null;
    public OffsetLimitRange(AbstractDBStyle style){
        this.sqlStyle = style;
    }

    @Override
    public String toRange(String jdbcSql, Object objOffset , Long limit) {
        Long offset = ((Number)objOffset).longValue();
        offset = PageParamKit.mysqlOffset(sqlStyle.offsetStartZero, offset);
        StringBuilder builder = new StringBuilder(jdbcSql);
        builder.append(" limit ").append(offset).append(" , ").append(limit);
        return builder.toString();
    }

    @Override
    public String toTemplateRange(Class mapping,String template) {
        return template + sqlStyle.getOrderBy() +
                " \nlimit " + sqlStyle.appendExpress( DBAutoGeneratedSql.OFFSET )
                + " , " + sqlStyle.appendExpress(DBAutoGeneratedSql.PAGE_SIZE);
    }

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