package com.keao.edu.thirdparty.message;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.keao.edu.thirdparty.exception.ThirdpartyException;

@Component
public class MessageSenderPluginContext {

	private MessageSenderPlugin messageSenderPlugin;

	private static final Map<String, MessageSenderPlugin> mapper = new HashMap<String, MessageSenderPlugin>();

	/**
	 * 发送消息至目的地
	 * @param pluginName 消息发送插件
	 * @param subject 消息主题
	 * @param content 消息内容
	 * @param receiver 收件人
	 * @param url 链接地址
	 * @param appClient app客户端
	 * @return 是否发送成功
	 * @throws IOException
	 */
	public boolean send(String pluginName, String subject, String content, String receiver, String url, String appClient) throws Exception {

		messageSenderPlugin = getMessageSenderPlugin(pluginName);

		return messageSenderPlugin.send(subject, content, receiver, url, appClient);
	}

	/**
	 * 批量发送消息至目的地
	 * @param pluginName 消息发送插件
	 * @param subject 消息主题
	 * @param content 消息内容
	 * @param receivers 收件人列表
	 * @param url 链接地址
	 * @return 是否发送成功
	 * @throws IOException
	 */
	public boolean batchSend(String pluginName, String subject, String content, String[] receivers, String url, String jpushType) throws Exception {

		messageSenderPlugin = getMessageSenderPlugin(pluginName);

		return messageSenderPlugin.batchSend(subject, content, receivers, url, jpushType);
	}

	public MessageSenderPlugin getMessageSenderPlugin(String pluginName) {
		MessageSenderPlugin messageSenderPlugin = mapper.get(pluginName);

		if (messageSenderPlugin == null) {
			throw new ThirdpartyException("消息提供方:{}不存在", pluginName);
		}

		return messageSenderPlugin;
	}

	public static void addMessageSender(MessageSenderPlugin messageSenderPlugin) {
		if (mapper.containsKey(messageSenderPlugin.getName())) {
			throw new ThirdpartyException("消息提供方:{}不存在", messageSenderPlugin.getName());
		}
		mapper.put(messageSenderPlugin.getName(), messageSenderPlugin);
	}

}
