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

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

import java.util.Collection;

/**
 * @Description 精确匹配
 * @Author: ph
 * @Date: 2019/12/11 16:57
 */
public class PreciseDateBaseAlgorithm implements PreciseShardingAlgorithm {

    @Override
    public String doSharding(Collection collection, PreciseShardingValue preciseShardingValue) {
        int hashCode = String.valueOf(preciseShardingValue.getValue()).hashCode();
        if (hashCode <= 0) {
            hashCode = 0 - hashCode;
        }
        int mod = hashCode % collection.size();
        ThreadContext.setDbSize(collection.size());
        for (Object each : collection) {
            String dsName = String.valueOf(each);
            if (dsName.endsWith(CommonConstants.SHARDING_SPLIT + mod)) {
                return dsName;
            }
        }
        throw new UnsupportedOperationException();
    }
}
