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.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 HintDataBaseAlgorithm 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);
        ThreadContext.setDbSize(collection.size());
        return doHintSharding(collection, preciseShardingValue.getValue());

    }

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