package com.bocloud.ims.service.monitor;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.bocloud.cmp.model.NotifyMessage;
import com.bocloud.common.enums.BoCloudExchange;
import com.bocloud.common.model.License;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.model.RequestContext.Catalog;
import com.bocloud.ims.repository.resource.ServerRepository;
import com.bocloud.service.core.CurrentService;
import com.bocloud.service.license.LicenseDaemon;

/**
 * license节点数扫描定时任务
 *
 * @author wangyu
 * @version 4.1.0-SNAPSHOT
 * @since 2019/3/22
 */
@Component
public class LicenseNodeScheduler implements InitializingBean {

	private static Logger logger = LoggerFactory.getLogger(LicenseNodeScheduler.class);
	/**
	 * 上次发送消息时间
	 */
	private static Date lastSendTime;
	private final LicenseDaemon licenseDaemon;
	@Autowired
	private CurrentService currentService;
	@Autowired
	private ServerRepository serverRepository;
	@Autowired
	private AmqpTemplate amqpTemplate;
	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public LicenseNodeScheduler(CurrentService currentService) {
		this.licenseDaemon = LicenseDaemon.instance(currentService);
	}

	/**
	 * 汇总所有物理机和虚拟机总节点数，如果发现license即将到期，则发送消息给用户进行通知
	 *
	 * @throws Exception
	 */
	@Scheduled(cron = "${license.node:0 0/1 * * * ?}")
	protected void monitor() throws Exception {
		if (!currentService.isLeader()) {
			return;
		}
		if (null == lastSendTime) {
			lastSendTime = new Date();
		}
		// 查询所有宿主机节点
		int nodeCount = serverRepository.licenseNodeCount();
		currentService.setCurrentNode(nodeCount);
		// 判断license是否即将过期
		License license = licenseDaemon.getLicenseContent();
		Date expireDate = license.getExpireDate();
		// 如果剩余license时间不足十天，则发送消息通知用户
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DAY_OF_YEAR, 10);
		if (null != expireDate) {
			return;
		}
		// 即将到期，通知用户
		if (calendar.getTime().after(expireDate)) {
			// 如果两次发送消息间隔大于10分钟，则再次发送消息通知用户
			calendar = Calendar.getInstance();
			calendar.add(Calendar.MINUTE, 10);
			if (calendar.getTime().after(lastSendTime)) {
				logger.info("Your license will expire 【" + format.format(expireDate)
						+ "】. If you need to continue using it, please contact the supplier!");
				lastSendTime = new Date();
				RequestContext context = new RequestContext(Catalog.Manager, null, null, null, null);
				NotifyMessage message = new NotifyMessage(context, "license到期预警",
						"您的license将于" + format.format(expireDate) + "过期，如需继续使用，请联系供应商！", true, false);
				amqpTemplate.convertAndSend(BoCloudExchange.Default.DIRECT.getExchange(), "event.notice.queue",
						message);
			}
		}
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.monitor();
	}
}
