package com.purui.prims.headless.server.listener;

import com.alibaba.fastjson.JSON;
import com.purui.prims.common.config.DolphinSchedulerConfig;
import com.purui.prims.common.pojo.GlobalAppData;
import com.purui.prims.headless.server.service.SysParameterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static com.purui.prims.dscheduler.constant.Constants.DOLPHINSCHEDULER;

/**
 * 初始化加载器
 *
 * @author charlie
 * @date 2024/8/1
 */
@Slf4j
@Component
public class InitLoadRunner implements CommandLineRunner {

    private final SysParameterService sysParameterService;

    @Resource
    private DolphinSchedulerConfig config;

    public InitLoadRunner(SysParameterService sysParameterService) {
        this.sysParameterService = sysParameterService;
    }

    @Override
    public void run(String... args) throws Exception {
        // 加载系统配置项
        log.info("init load runner");
        sysParameterService.getParameterList().forEach(sysParameterDO -> {
            String key = sysParameterDO.getName();
            Object value = sysParameterDO.getDataValue();
            if (value == null) {
                // 默认值
                value = sysParameterDO.getDefaultValue();
            }
            GlobalAppData.getInstance().setConfig(key, value);
        });
        // 覆盖默认配置项
        initDolphinSchedulerConfig();
    }

    /**
     * DolphinScheduler的配置，优先从数据库中读取
     */
    private void initDolphinSchedulerConfig() {
        if (GlobalAppData.getInstance().exists(DOLPHINSCHEDULER)) {
            String dolphinscheduler = GlobalAppData.getInstance().getConfig(DOLPHINSCHEDULER).toString();
            if (dolphinscheduler != null) {
                // 必须单独解析，否则会忽略
                DolphinSchedulerConfig newConfig = JSON.parseObject(dolphinscheduler, DolphinSchedulerConfig.class);
                config.setTargetName(newConfig.getTargetName());
                config.setTargetType(newConfig.getTargetType());
                config.setSourceName(newConfig.getSourceName());
                config.setSourceType(newConfig.getSourceType());
                config.setToken(newConfig.getToken());
                config.setUrl(newConfig.getUrl());
            }
        } else {
            GlobalAppData.getInstance().setConfig(DOLPHINSCHEDULER, JSON.toJSONString(config));
        }

    }
}
