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 {

	public enum MessageSender {

		JIGUANG("PUSH"), MOXINGTONG("SMS"), SHIYUAN("SMS"), YIMEI("SMS");

		/**
		 * 发送模式（SMS,PUSH,EMAIL）
		 */
		private String sendMode;

		private MessageSender(String sendMode) {
			this.sendMode = sendMode;
		}

		public String getSendMode() {
			return sendMode;
		}
	}

	private MessageSenderPlugin messageSenderPlugin;

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

	/**
	 * 发送消息至目的地
	 * @param messageSender 消息发送方
	 * @param subject 消息主题
	 * @param content 消息内容
	 * @param receiver 收件人
	 * @param url 链接地址
	 * @return 是否发送成功
	 * @throws IOException
	 */
	public boolean send(MessageSender messageSender, String subject, String content, String receiver, String url, String jpushType) throws Exception {

		messageSenderPlugin = getMessageSenderPlugin(messageSender);

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

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

		messageSenderPlugin = getMessageSenderPlugin(messageSender);

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

	private MessageSenderPlugin getMessageSenderPlugin(MessageSender messageSender) {
		MessageSenderPlugin messageSenderPlugin = mapper.get(messageSender.name());

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

		return messageSenderPlugin;
	}

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

}
