package com.fdage.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Hb_zzZ on 2019/9/16.
 */
@ApiIgnore
@WebServlet(urlPatterns = { "/sendMessage" }, asyncSupported = true)
@Controller
public class SseController extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private final static int DEFAULT_TIME_OUT = 10 * 60 * 1000;
    public static List<AsyncContext> actxList =new ArrayList<AsyncContext>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        resp.setContentType("text/event-stream");
        resp.setCharacterEncoding("UTF-8");
        req.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);//注意这里

        AsyncContext actx = req.startAsync(req, resp);
        actx.setTimeout(DEFAULT_TIME_OUT);
        actx.addListener(new AsyncListener() {
            @Override
            public void onComplete(AsyncEvent arg0) throws IOException {
                // TODO Auto-generated method stub
                System.out.println("[echo]event complete:" + arg0.getSuppliedRequest().getRemoteAddr());
            }

            @Override
            public void onError(AsyncEvent arg0) throws IOException {
                // TODO Auto-generated method stub
                System.out.println("[echo]event has error");
            }

            @Override
            public void onStartAsync(AsyncEvent arg0) throws IOException {
                // TODO Auto-generated method stub
                System.out.println("[echo]event start:" + arg0.getSuppliedRequest().getRemoteAddr());
            }

            @Override
            public void onTimeout(AsyncEvent arg0) throws IOException {
                // TODO Auto-generated method stub
                System.out.println("[echo]event time lost");
            }
        });

        actxList.add(actx);

//        PrintWriter out = actx.getResponse().getWriter();
//        out.println("data:" + new Date().getTime());  //js页面EventSource接收数据格式：data：数据 + "\r\n"
//        out.flush();
//        new Thread(new AsyncWebService(actx)).start();
    }

    @GetMapping("send")
    @ResponseBody
    public static String send(String msg){
        //打印当前AsyncContext
        System.out.println(actxList.size());
        if(actxList.size()>0){
            for(int i = 0;i<actxList.size();i++){
                AsyncContext obj = actxList.get(i);
                PrintWriter out;

                try {
                    if (obj.getTimeout()>0){
                        out = obj.getResponse().getWriter();
                        out.println(msg);  //js页面EventSource接收数据格式：data：数据 + "\r\n"
                        out.flush();
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return "发送消息";
    }

//    class AsyncWebService implements Runnable {
//        AsyncContext ctx;
//
//        public AsyncWebService(AsyncContext ctx) {
//            this.ctx = ctx;
//        }
//
//        public void run() {
//            try {
//                //等待十秒钟，以模拟业务方法的执行
//                Thread.sleep(10000);
//                PrintWriter out = ctx.getResponse().getWriter();
//                out.println("data:中文" + new Date() + "\r\n");  //js页面EventSource接收数据格式：data：数据 + "\r\n"
//
//                out.flush();
//                ctx.complete();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//        }
//
//    }
}
