package com.uas.search.console.service.impl;

import java.net.Inet4Address;
import java.net.UnknownHostException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.uas.message.sms.service.SmsService;
import com.uas.search.console.SystemProperties;
import com.uas.search.console.dao.LuceneQueueMessageDao;
import com.uas.search.console.jms.AQListener;
import com.uas.search.console.model.LuceneQueueMessage;
import com.uas.search.console.schedule.model.TaskInformation;
import com.uas.search.console.schedule.service.Executable;
import com.uas.search.console.schedule.service.TaskService;
import com.uas.search.console.service.RealTimeUpdateMonitorService;
import com.uas.search.model.SPage;

/**
 * 创建定时任务，监控实时更新异常情况
 * 
 * @author sunyj
 * @since 2016年12月19日 下午3:40:03
 */
@Service
public class RealTimeUpdateMonitorServiceImpl implements RealTimeUpdateMonitorService {

	@Autowired
	private TaskService taskService;

	@Autowired
	private LuceneQueueMessageDao luceneQueueMessageDao;

	@Autowired
	private SmsService smsService;

	@Autowired
	private SystemProperties systemProperties;

	/**
	 * 上次查询时最旧的消息
	 */
	private LuceneQueueMessage oldestMessage;

	@Autowired
	private AQListener aqListener;

	/**
	 * 第一次执行的延迟时间间隔为1秒
	 */
	private static final long INITIAL_DELAY = 1000;

	/**
	 * 两次任务之间的等待时间间隔为5分钟
	 */
	private static final long PERIOD = 5 * 60 * 1000;

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public TaskInformation newTask() {
		String title = "监控实时更新异常情况";
		Executable command = new Executable() {
			@Override
			public String execute() {
				// 如果实时更新未正常运行，发送警告短信并自动重启实时更新服务
				if (!workWell()) {
					logger.error("实时更新未正常运行");
					logger.info("发送警告短信...");
					sendWarnSms();
					if (aqListener.isRunning()) {
						aqListener.stop();
					}
					aqListener.start(null);
					return "异常";
				}
				return "正常";
			}
		};
		TaskInformation taskInformation = new TaskInformation(title, command, INITIAL_DELAY, PERIOD);
		taskService.newTask(taskInformation);
		return taskInformation;
	}

	/**
	 * 实时更新服务是否运行良好
	 * 
	 * @return true 如果运行良好
	 */
	private boolean workWell() {
		SPage<LuceneQueueMessage> sPage = luceneQueueMessageDao.findAll(1, 1, null);
		// 如果消息队列中没有消息，说明没有等待更新的消息
		if (sPage.getTotalElement() == 0) {
			return true;
		}
		LuceneQueueMessage luceneQueueMessage = sPage.getContent().get(0);
		// 比较上次与本次查询的最旧的消息，如果两者相同，说明实时更新服务出现了问题
		if (oldestMessage != null && oldestMessage.equals(luceneQueueMessage)) {
			return false;
		} else {
			oldestMessage = luceneQueueMessage;
			return true;
		}
	}

	/**
	 * 发送警告短信
	 */
	private void sendWarnSms() {
		String message = "B2C实时更新服务出现问题，正在自动重启实时更新服务";
		try {
			message += "，来自" + Inet4Address.getLocalHost().toString();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		smsService.sendAll(systemProperties.getSmsTemplateId(), systemProperties.getSmsReceivers(),
				new Object[] { message });
	}

}
