package com.ym.mec.thirdparty.adapay;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.huifu.adapay.Adapay;
import com.huifu.adapay.model.MerConfig;
import com.ym.mec.thirdparty.adapay.entity.HfMerchantConfig;
import com.ym.mec.thirdparty.exception.ThirdpartyException;

/**
 * 系统初始化
 */
public class AdapayInit {

	/**
	 * debug 模式，开启后与详细的日志
	 */
	private boolean debug;

	/**
	 * prodMode 模式，默认为生产模式，false可以使用mock模式
	 */
	private boolean prodMode;

	private static AdapayInit init;

	private AdapayInit(boolean debug, boolean prodMode) {
		this.debug = debug;
		this.prodMode = prodMode;
	}

	public static AdapayInit getInstance(boolean debug, boolean prodMode) {
		if (init == null) {
			init = new AdapayInit(debug, prodMode);
		}

		return init;
	}

	public boolean initWithMerConfig(List<HfMerchantConfig> adapayMerConfigList) {
		
		Adapay.debug = debug;
		Adapay.prodMode = prodMode;
		
		Map<String, MerConfig> configPathMap = new HashMap<String, MerConfig>();

		for (HfMerchantConfig adapayMerConfig : adapayMerConfigList) {
			MerConfig merConfig = new MerConfig();
			merConfig.setApiKey(adapayMerConfig.getApiKey());
			merConfig.setApiMockKey(adapayMerConfig.getMockApiKey());
			merConfig.setRSAPrivateKey(adapayMerConfig.getRsaPrivateKey());
			
			configPathMap.put(adapayMerConfig.getMerKey(), merConfig);
		}
		
		try {
			Adapay.initWithMerConfigs(configPathMap);
		} catch (Exception e) {
			throw new ThirdpartyException("汇付商户配置初始化失败:{}", e, e.getMessage());
		}

		return true;
	}
}
