package com.community.huiju.controller;

import com.community.commom.mode.ResponseBean;
import com.community.huiju.common.base.BaseController;
import com.community.huiju.service.IMqMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Random;

@RestController
@RefreshScope
@RequestMapping("/")
@Api(value = "订阅事件",description = "订阅事件")
public class MqMessageController extends BaseController {

    @Autowired
    private IMqMessageService iMqMessageService;

    @ApiOperation(value = "统计开门次数", notes = "统计开门次数")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header",dataType = "String",name = "X-Auth-Token",value = "Token"),
    })
    @RequestMapping(value = "/mq/open",method = RequestMethod.GET)
    public ResponseBean getOpenDoor(){
        ResponseBean responseBean = new ResponseBean();
        responseBean = iMqMessageService.selectOpenDoorCount();
        return responseBean;
    }
    
    @ApiOperation(value = "长连接", notes = "长连接")
    @ApiImplicitParams({
    })
    @RequestMapping(value = "/mq/connection",method = RequestMethod.GET)
    public ResponseBean ajax(HttpServletResponse response) throws Exception {
        Long startTime = System.currentTimeMillis();
        // 死循环 查询有无数据变化
        while (true) {
            Long endTime = System.currentTimeMillis();
            if (endTime - startTime > 8000){
                return null;
            }
            // 获取开门次数的状态值
            String status = iMqMessageService.getConnectionByName();
            if (status.equals("1")) {
                iMqMessageService.updateConnectionByName();
                return getOpenDoor();
            } else { // 模拟没有数据变化，将休眠 hold住连接
                Thread.sleep(5000);
            }
        }
        
    }
}
