package com.xt.hb.data.core;

import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.xt.hb.data.camera.svcimpl.CameraService;
import com.xt.hb.data.cbyj.svcimpl.CbyjService;
import com.xt.hb.data.service.FetchService;
import com.xt.hb.data.system.svc.SystemService;

/**
 * 定时任务Servlet
 * 
 * @author 袁晓冬
 *
 */
public class InitServlet extends HttpServlet {
	private final Logger log = LoggerFactory.getLogger(InitServlet.class);

	/** serialVersionUID */
	private static final long serialVersionUID = 3137976979537814808L;
	private AutowireCapableBeanFactory beanFactory;
	private ScheduledExecutorService executor;

	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		beanFactory = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext())
				.getAutowireCapableBeanFactory();
		executor = Executors.newScheduledThreadPool(5);
		SystemService systemService = beanFactory.getBean(SystemService.class);
		systemService.reloadParam();
		initAllService();
		log.info("system init success!!");
		System.err.println("system init success!!");
	}

	/**
	 * 初始化服务
	 */
	private void initAllService() {
		// 船舶预警服务
		FetchService cbyjService = beanFactory.getBean(CbyjService.class);
		FetchService cameraService = beanFactory.getBean(CameraService.class);
		executor.scheduleAtFixedRate(new FetchTask(cbyjService, executor, 10), 0, 20, TimeUnit.SECONDS);
		executor.scheduleAtFixedRate(new FetchTask(cameraService, executor, 10), getMillis0100(), 1, TimeUnit.DAYS);
	}

	/**
	 * 获取下个整点间隔
	 * 
	 * @return
	 */
	private static long getMillis0100() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DATE, 1);
		c.set(Calendar.HOUR, 1);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTimeInMillis()-System.currentTimeMillis();
	}
}
