package com.zm.order.tool.server.sharding;

import org.springframework.util.StringUtils;

import java.util.regex.Pattern;

/**
 * 功能：物理表路由表达shi
 *
 * @author chuchengyi
 */
public class HintTableExpression {

    private static final String EXPRESSION_PRE_FIX = "HINT_";


    private static final String EXPRESSION_SUB_FIX = "_END";


    private static final String EXPRESSION_PATTERN = EXPRESSION_PRE_FIX + "[0-9]+" + EXPRESSION_SUB_FIX;


    /**
     * 功能：生成物理表的路由key
     *
     * @param index
     * @return
     */
    public static String genExpression(int index) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(EXPRESSION_PRE_FIX);
        buffer.append(index);
        buffer.append(EXPRESSION_SUB_FIX);
        return buffer.toString();
    }


    /**
     * 功能：判断是否是物理表路由
     *
     * @param expression
     * @return
     */
    public static boolean matchExpression(String expression) {
        //判断数据是否为空
        if (expression == null || expression.isEmpty()) {
            throw new NullPointerException("hit expression is null:" + expression);
        }
        boolean isMatch = Pattern.matches(EXPRESSION_PATTERN, expression);
        return isMatch;
    }


    /**
     * 功能：根据具体内容获取具体的表路由信息
     *
     * @param expression
     * @return
     */
    public static int getTableIndex(String expression) {
        if (!StringUtils.isEmpty(expression)) {
            expression = expression.replace(EXPRESSION_PRE_FIX, "");
            expression = expression.replace(EXPRESSION_SUB_FIX, "");
            return Integer.parseInt(expression);

        }
        return 0;
    }

    /**
     * 功能：根据具体内容获取具体的数据库路由信息
     *
     * @param expression 数据库串
     * @return 返回数据库的index
     */
    public static int getDataBaseIndex(String expression) {
        return getTableIndex(expression);
    }


}
