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;

/**
 * 需要显示的提供offset关键字
 * @author xiandafu
 */
public class LimitWithOffsetRange implements RangeSql {
    AbstractDBStyle sqlStyle = null;
    public LimitWithOffsetRange(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(limit);
        builder.append(" offset ").append(offset);
        return builder.toString();
    }

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

    @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);
    }
}