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


import com.zm.order.tool.server.constants.CommonConstants;
import org.apache.shardingsphere.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.hint.HintShardingValue;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Description Hint强制路由表算法
 * @Author: ph
 * @Date: 2019/11/25 10:40
 */
@Component
public class HintTableAlgorithm extends AbstractHintAlgorithm implements HintShardingAlgorithm<String> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, HintShardingValue<String> hintShardingValue) {
        HintShardingValue<String> tempHintShardingValue = hintShardingValue;
        PreciseShardingValue<String> preciseShardingValue = this.convert(tempHintShardingValue);
        return doHintSharding(collection, preciseShardingValue.getValue());
    }

    public Collection<String> doHintSharding(Collection<String> collection, String shardingValue) {
        List<String> result = new ArrayList<>();
        int mod = HintTableExpression.getTableIndex(shardingValue);
        mod = mod % collection.size();
        for (String each : collection) {
            if (each.endsWith(CommonConstants.SHARDING_SPLIT + mod)) {
                result.add(each);
            }
        }
        return result;
    }
}
