package org.springblade.datasource.transform;

import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springblade.etl.entity.SqlColumn;
import org.springblade.etl.service.SqlColumnService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class RunnerLoadOne implements CommandLineRunner {
    static Map<Integer, List<SqlColumn>> sqlColumnMap = new ConcurrentHashMap<>();

    @Resource
    private SqlColumnService service;

    public static List<SqlColumn> getInfo(Integer dsType) {
        return sqlColumnMap.get(dsType);
    }

    @Override
    public void run(String... args) throws Exception {
        List<SqlColumn> list1 = service.lambdaQuery().list();
        Optional.ofNullable(list1).ifPresent(list -> {

            list.stream().forEach(v -> {
                List<SqlColumn> sqlColumns = sqlColumnMap.get(v.getDsType());
                if (CollectionUtils.isEmpty(sqlColumns)) {
                    sqlColumnMap.put(v.getDsType(), Lists.newArrayList(v));
                    return;
                }
                sqlColumns.add(v);
            });

        });
    }

    /**
     * 为map缓存赋值一份新的指向
     */
    public static void setInfo(Map<Integer, List<SqlColumn>> sqlColumnMap) {
        if (sqlColumnMap != null && !sqlColumnMap.isEmpty()) {
            RunnerLoadOne.sqlColumnMap = sqlColumnMap;
        }

    }

}
