package cn.myapps.support.sms;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.myapps.authtime.common.dao.PersistenceUtils;
import cn.myapps.common.util.StringUtil;
import cn.myapps.support.sms.SMSMode.SMSParcels;

/**
 * 手机短信发送接收操作类
 * 
 * @author Happy
 * 
 */
public class SMSQueueOperator {

	private static final Logger log = LoggerFactory.getLogger(SMSQueueOperator.class);

	private Object notEmpty = new Object();

	private Thread thread = new SendSMSThread();
	/**
	 * 待发送的短信队列
	 */
	private Queue<SMSParcels> smsQueue = new ConcurrentLinkedQueue<SMSParcels>();

	private volatile static SMSQueueOperator instance;

	public static SMSQueueOperator getInstance() {
		if (instance == null) {
			synchronized (SMSQueueOperator.class) {
				if (instance == null)
					instance = new SMSQueueOperator();
			}
		}
		return instance;

	}

	/**
	 * 加入发送队列
	 * 
	 * @param parcels
	 */
	public void add(SMSParcels parcels) {
		smsQueue.add(parcels);
		
		if (!this.thread.isInterrupted()) {
		synchronized (notEmpty) {
			if(!smsQueue.isEmpty()){
				notEmpty.notifyAll();
				log.debug("{}", "SMS sending thread is wake up!");
				}
			}
		}
		
	}

	/**
	 * 启动发送线程
	 */
	public void send() {
		if (!thread.isAlive()) {
			thread.start();
			log.debug("{}", "SMS sending thread is started");
		}
	}

	/**
	 * 短信发送的线程
	 */
	public class SendSMSThread extends Thread {

		public void run() {
			while (true) {
				synchronized (notEmpty) {
					if (!smsQueue.isEmpty()) {

						SMSParcels parcels = smsQueue.poll();
						if (parcels != null) {
							try {

								MessageManager manager = MessageManager.getInstance(new Validator(parcels.getDomainid(), parcels.getApplication()));
								ISender sender = manager.getSender();

								String[] receiver = parcels.getReceiver();
								String replyCode = "";
								
								if (sender != null) {
									String contents = parcels.getContent()+ parcels.getSign().trim();
									contents = contents.replace('\n', ' ');
									contents = contents.replace('\r', ' ');
									contents = contents.replace(
											"&#160;&#160;&#160;", " ");
									contents = contents.replace("</br>", " ");
									int result = -100;
									if (receiver != null && receiver.length == 1) {
										if (StringUtil.isBlank(replyCode)) {
											result = sender.sendMessage(receiver[0], contents);
										}
										else{
											result = sender.sendMessage(receiver[0], contents,replyCode);
										}
									} else if (receiver != null && receiver.length > 1) {
										if (StringUtil.isBlank(replyCode))
											result = sender.battchSendMessage(receiver, contents);
										else
											result = sender.battchSendMessage(receiver, contents,replyCode);
									}

									if (result < 0) {
										parcels.feedback(false);
									} else {
										parcels.feedback(true);
									}
								}

							} catch (Exception e) {
								e.printStackTrace();
							}finally{
									try {
										PersistenceUtils.closeSessionAndConnection();
									} catch (Exception e) {
										e.printStackTrace();
									}
							}

						}

					}else{
						try {
							notEmpty.wait();
							log.debug("{}", "SMS sending thread waiting......");
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}

	}
	

}
