package com.qiaoba.common.database.context;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import com.qiaoba.common.database.entity.DynamicDataSource;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 备用(未在使用)数据源
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/6/28 10:36
 */
public class BackupDatasourceContext {

    /**
     * 备用数据源
     */
    private static Map<String, List<DynamicDataSource>> BACKUP_DATASOURCE_MAP = new ConcurrentHashMap<>();


    /**
     * 获取租户备用数据源
     *
     * @param tenantId 租户ID
     * @return 数据源集合
     */
    public static List<DynamicDataSource> get(String tenantId) {
        return BACKUP_DATASOURCE_MAP.get(tenantId);
    }

    /**
     * 设置租户备用数据源
     *
     * @param tenantId 租户ID
     * @param list     数据源集合
     */
    public static void set(String tenantId, List<DynamicDataSource> list) {
        BACKUP_DATASOURCE_MAP.put(tenantId, list);
    }

    /**
     * 添加租户备用数据源
     *
     * @param tenantId   租户ID
     * @param dataSource 数据源
     */
    public static void addBackupMap(String tenantId, DynamicDataSource dataSource) {
        List<DynamicDataSource> dataSourceList = get(tenantId);
        if (CollUtil.isEmpty(dataSourceList)) {
            set(tenantId, ListUtil.toList(dataSource));
        } else {
            dataSourceList.add(dataSource);
        }
    }

    /**
     * 删除租户备用数据源
     *
     * @param tenantId     租户ID
     * @param dataSourceId 数据源ID
     */
    public static void delBackupMap(String tenantId, String dataSourceId) {
        List<DynamicDataSource> dataSourceList = get(tenantId);
        if (CollUtil.isEmpty(dataSourceList)) {
            for (DynamicDataSource dynamicDataSource : dataSourceList) {
                if (dataSourceId.equals(dynamicDataSource.getDatasourceId())) {
                    dataSourceList.remove(dynamicDataSource);
                    break;
                }
            }
        }
    }

    /**
     * 修改租户备用数据源
     *
     * @param tenantId   租户ID
     * @param dataSource 数据源
     */
    public static void updateBackupMap(String tenantId, DynamicDataSource dataSource) {
        List<DynamicDataSource> dataSourceList = get(tenantId);
        if (CollUtil.isEmpty(dataSourceList)) {
            for (DynamicDataSource dynamicDataSource : dataSourceList) {
                if (dataSource.getDatasourceId().equals(dynamicDataSource.getDatasourceId())) {
                    dataSourceList.remove(dynamicDataSource);
                    dataSourceList.add(dataSource);
                    break;
                }
            }
        }
    }
}
