package org.beetl.sql.core.nosql;

import org.beetl.sql.core.SQLSource;
import org.beetl.sql.core.db.AbstractDBStyle;
import org.beetl.sql.core.db.DBAutoGeneratedSql;
import org.beetl.sql.core.db.DBType;
import org.beetl.sql.core.db.PageParamKit;
import org.beetl.sql.core.range.RangeSql;

import java.util.Map;

/**
 *  hbase
 * @author xiandafu
 *
 */
public class HBaseStyle extends AbstractDBStyle {
    RangeSql rangeSql = null;
    public HBaseStyle() {
        super();
        rangeSql = new HbaseRange(this);
    }

    @Override
    public int getIdType(Class c,String idProperty) {
        return DBType.ID_ASSIGN;
    }

    @Override
    public boolean  isNoSql(){
        return true;
    }
    @Override
    public String getName() {
        return "hbase";
    }

    @Override
    public int getDBType() {
        return DBType.DB_HBASE;
    }

    @Override
    public RangeSql getRangeSql() {
        return rangeSql;
    }


    @Override
    protected SQLSource generalInsert(Class<?> cls, boolean template){
        SQLSource sqlSource   = super.generalInsert(cls,template);
        String upsert = sqlSource.template.replaceFirst("insert","UPSERT");
        sqlSource.template = upsert;
        return sqlSource;
    }

    @Override
    public SQLSource genUpdateById(Class<?> cls) {
       return this.generalInsert(cls,false);
    }


    static  class HbaseRange  implements   RangeSql{
        AbstractDBStyle sqlStyle = null;
        public HbaseRange(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).append(" offset ").append(limit);
            return builder.toString();
        }

        @Override
        public String toTemplateRange(Class mapping,String template) {
            return template + sqlStyle.getOrderBy()
                    +" \n limit " + sqlStyle.appendExpress( DBAutoGeneratedSql.PAGE_SIZE )
                    +" \n 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);
        }
    }



}
