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

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