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

import com.zm.order.tool.server.component.ThreadContext;
import com.zm.order.tool.server.constants.CommonConstants;
import com.zm.order.tool.server.manager.RoutingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.util.Assert;

import java.util.Collection;


/**
 * 新节点数据表路由算法
 *
 * @author nianchang
 * @date 2022/03/29 3:57 下午
 */
public class NewCommonNumberPreciseTableAlgorithm implements PreciseShardingAlgorithm {

    @Override
    public String doSharding(Collection collection, PreciseShardingValue psv) {
        Assert.notNull(psv.getValue(), "tb route shard key is null!");
        Assert.notNull(ThreadContext.getDbSize(), "db size is null!");
        final int tbSize = collection.size();
        int dbSize = ThreadContext.getDbSize();
        int mod = RoutingAlgorithm.routeTB(Long.parseLong(psv.getValue().toString()), dbSize, tbSize);
        for (Object each : collection) {
            String tbName = String.valueOf(each);
            if (tbName.endsWith(CommonConstants.SHARDING_SPLIT + mod)) {
                return tbName;
            }
        }
        throw new UnsupportedOperationException();
    }
}
