package de.ctdo.bunti.websocket;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.Broadcaster;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class WebSocketController {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketController.class);


    @RequestMapping(value="/buntisocket", method=RequestMethod.GET)
    @ResponseBody
    public void websockets(final AtmosphereResource<HttpServletRequest,HttpServletResponse> event) {



        final HttpServletRequest  req = event.getRequest();
//        final HttpServletResponse res = event.getResponse();

        LOGGER.debug("call to websockets " + req.toString());

        final ObjectMapper mapper = new ObjectMapper();

        event.suspend();

        final Broadcaster bc = event.getBroadcaster();

        bc.scheduleFixedBroadcast(new Callable<String>() {

            private long sinceId = 0;

            @Override
            public String call() throws Exception {
                LOGGER.debug("call was called");

                return mapper.writeValueAsString("blafaselblubb");
            }

        }, 10, TimeUnit.SECONDS);

    }

}

