package com.suvalue.dynamic.datasource;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class DataSourceContextHolder {
    private static final ThreadLocal<String> context = new ThreadLocal<String>();
    private static final String MASTER = "master";
    private static final String SLAVE = "slave";
    private static final AtomicInteger counter = new AtomicInteger(-1);
    private static List<String> listSlave = new ArrayList<>();

    public synchronized static String addSlave(){
        String slave = SLAVE + listSlave.size();
        listSlave.add(slave);
        return slave;
    }

    public static void master(){
        setDataSource(MASTER);
    }

    public static void slave(){
        if(listSlave.size() >= 0){
            int index = counter.getAndSet(counter.getAndIncrement()%listSlave.size());
            String slave = listSlave.get(index);
            setDataSource(slave);
        }else{
            master();
        }
    }

    public static String getDataSource(){
        return context.get();
    }

    public static void setDataSource(String dataSource){
        context.set(dataSource);
    }

    public static void clear(){
        context.remove();
    }

}
