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 NewCommonNumberPreciseDataBaseAlgorithm implements PreciseShardingAlgorithm {

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