package com.philisense.www.dynamic.druid.conf;

import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据源切换处理
 * 
 */
public class DynamicDataSourceContextHolder
{
    public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);

    /**
     * 使用ThreadLocal维护变量，ThreadLocal为每个使用该变量的线程提供独立的变量副本，
     *  所以每一个线程都可以独立地改变自己的副本，而不会影响其它线程所对应的副本。
     */
    private static final ThreadLocal<DynamicDruidDataSourceTypeEnum> CONTEXT_HOLDER = new ThreadLocal<DynamicDruidDataSourceTypeEnum>();
    
    private static final AtomicInteger counter = new AtomicInteger(-1);

    /**
     * 设置数据源的变量
     */
    public static void setDataSourceType(DynamicDruidDataSourceTypeEnum dsType)
    {
        
        CONTEXT_HOLDER.set(dsType);
    }
    
    /**
     * 设置主数据源的变量
     */
    public static void setMasterDataSourceType()
    {
        
        setDataSourceType(DynamicDruidDataSourceTypeEnum.MASTER);
    }
    /**
     * 设置从数据源的变量
     */
    public static void setSlaveDataSourceType(DynamicDataSource dynamicDataSource) {
        //  轮询
        int index = counter.getAndIncrement() % 4;
        if (counter.get() > 9999) {
            counter.set(-1);
        }
        if (index == 0) {
        	if( null == dynamicDataSource.getRouterTargetDataSources().get(DynamicDruidDataSourceTypeEnum.SLAVE1)) {
            	setDataSourceType(DynamicDruidDataSourceTypeEnum.MASTER);
        	}else {
	        	setDataSourceType(DynamicDruidDataSourceTypeEnum.SLAVE1);
        	}
        	
        }else if (index == 1) {
        	if( null == dynamicDataSource.getRouterTargetDataSources().get(DynamicDruidDataSourceTypeEnum.SLAVE2)) {
            	setDataSourceType(DynamicDruidDataSourceTypeEnum.MASTER);
        	}else {
	        	setDataSourceType(DynamicDruidDataSourceTypeEnum.SLAVE2);
        	}
        }else if (index == 2) {
        	if( null == dynamicDataSource.getRouterTargetDataSources().get(DynamicDruidDataSourceTypeEnum.SLAVE3)) {
            	setDataSourceType(DynamicDruidDataSourceTypeEnum.MASTER);
        	}else {
	        	setDataSourceType(DynamicDruidDataSourceTypeEnum.SLAVE3);
        	}
        }else if (index == 3) {
        	if( null == dynamicDataSource.getRouterTargetDataSources().get(DynamicDruidDataSourceTypeEnum.SLAVE4)) {
            	setDataSourceType(DynamicDruidDataSourceTypeEnum.MASTER);
        	}else {
	        	setDataSourceType(DynamicDruidDataSourceTypeEnum.SLAVE4);
        	}
        } else  {
	        	setDataSourceType(DynamicDruidDataSourceTypeEnum.MASTER);
        }
    }

    /**
     * 获得数据源的变量
     */
    public static DynamicDruidDataSourceTypeEnum getDataSourceType()
    {
        return CONTEXT_HOLDER.get();
    }

    /**
     * 清空数据源变量
     */
    public static void clearDataSourceType()
    {
        CONTEXT_HOLDER.remove();
    }
    
    
}
