package weaver.interfaces.htsc.payment.common;

import com.engine.htsc.init.payment.impl.PDFProcessorInitServcieImpl;
import weaver.general.BaseBean;
import weaver.interfaces.htsc.payment.common.pdfprocess.PDFBizProcessorImpl;
import weaver.interfaces.htsc.payment.common.pdfprocess.PdfConsumer;
import weaver.interfaces.htsc.payment.common.pdfprocess.PdfProducer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created on 2022/4/15.
 * 配置启动类方案已从web.xml替换成
 * @see PDFProcessorInitServcieImpl
 *
 * @author K1810012
 */
public class PDFProcessorListener implements ServletContextListener {

  @Override
  public void contextInitialized(ServletContextEvent servletContextEvent) {
    new BaseBean().writeLog("===>>> pdf sync listener thread start....");
    new BaseBean().writeLog("===>>> pdf sync listener thread start....");
    new BaseBean().writeLog("===>>> pdf sync listener thread start....");

    PDFBizProcessorImpl pdfBizProcessor = new PDFBizProcessorImpl();
    LinkedBlockingDeque<Runnable> runnables = new LinkedBlockingDeque<>(10);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
        10, 20, 5L, TimeUnit.SECONDS,
        new LinkedBlockingQueue<>(10),
        new ThreadPoolExecutor.CallerRunsPolicy());
    //2:1
    for (int i = 0; i < 5; i++) {
      try {
        runnables.put(new PdfConsumer(pdfBizProcessor, runnables));
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    PdfProducer producer = new PdfProducer(pdfBizProcessor, runnables, threadPoolExecutor);
    new Thread(producer).start();
  }

  @Override
  public void contextDestroyed(ServletContextEvent servletContextEvent) {

  }
}
