package cn.myapps.runtime.workflow.notification.ejb;

import java.util.Collection;
import java.util.Iterator;

import cn.myapps.scheduler.Job;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.myapps.authtime.common.dao.PersistenceUtils;
import cn.myapps.common.model.application.Application;
import cn.myapps.designtime.application.service.ApplicationDesignTimeService;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.runtime.common.service.RunTimeServiceManager;
import org.springframework.scheduling.quartz.QuartzJobBean;

@PersistJobDataAfterExecution // 当job执行结束，持久化job信息到数据库
@DisallowConcurrentExecution // 保证job的唯一性（单例）
public class NotificationJob extends Job {
	public final static Logger LOG = LoggerFactory.getLogger(NotificationJob.class);
	
	public final static Object _lock = new Object();

	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		synchronized (_lock) {
			try {
				LOG.debug("{}", "********************* Notification Job Start ********************");
				ApplicationDesignTimeService appService = DesignTimeServiceManager.applicationDesignTimeService();
				Collection<Application> applications = appService.list(null,null);
				try {
					for (Iterator<Application> iterator = applications.iterator(); iterator.hasNext();) {
						Application application = (Application) iterator.next();
						if (application.testDB()) {
							try {
								NotificationProcess process = RunTimeServiceManager.notificationProcess(application.getId());
								process.notifyOverDueAuditors();
							} catch (Exception e) {
								continue;
							} finally {
								PersistenceUtils.closeSessionAndConnection();
							}
						}
					}
				} catch (Exception e) {
					LOG.error("Notification Job Error: ", e);
				}
	
				LOG.debug("{}", "********************* Notification Job End ********************");
			} catch (Exception e) {
				LOG.error("Notification Job Error: ", e);
			} finally {
				try {
					PersistenceUtils.closeSessionAndConnection();
				} catch (Exception e) {
					LOG.error("Notification Job Error: ", e);
				}
			}
		}
	}
}
