package com.ycwl.basic.pay.starter;

import com.ycwl.basic.pay.PayFactory;
import com.ycwl.basic.pay.adapter.IPayAdapter;
import com.ycwl.basic.pay.starter.config.OverallPayConfig;
import com.ycwl.basic.pay.starter.config.PayConfigItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PayAutoConfiguration {
    private final OverallPayConfig config;
    public PayAutoConfiguration(OverallPayConfig config) {
        this.config = config;
        if (config != null) {
            if (config.getConfigs() != null) {
                loadConfig();
            }
            if (StringUtils.isNotBlank(config.getDefaultUse())) {
                PayFactory.setDefault(config.getDefaultUse());
            }
        }
    }

    private void loadConfig() {
        for (PayConfigItem item : config.getConfigs()) {
            IPayAdapter adapter = PayFactory.getAdapter(item.getType());
            adapter.loadConfig(item.getConfig());
            PayFactory.register(item.getName(), adapter);
        }
    }
}
