package motoSample;

import org.atmosphere.config.service.Disconnect;
import org.atmosphere.config.service.ManagedService;
import org.atmosphere.config.service.Ready;
import org.atmosphere.config.service.Get;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResourceEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;

import static org.atmosphere.cpr.ApplicationConfig.MAX_INACTIVE;

///ManagedService for url access under: /comet/*
@ManagedService(path = "/comet/{a-zA-Z0-9_-}*", atmosphereConfig = MAX_INACTIVE + "=120000")
public class AtmosRes {
    private final Logger logger = LoggerFactory.getLogger(AtmosRes.class);

    /**
     * Invoked when the connection as been fully established and suspended, e.g ready for receiving messages.
     *
     * @param r
     */
    @Ready
    public void onReady(final AtmosphereResource r) {
        logger.info("Browser {} connected.", r.uuid());
    }

    void outputSessionError(AtmosphereResource r) {
        HttpServletResponse response = r.getResponse();
        PushMsg pm = PushMsg.newSessionErrorMessage();
        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(pm);
            r.write(json);
            r.close();
        } catch (IOException e) {
            logger.error("json write error");
        }
    }
    
    @Get
    public void onGet(final AtmosphereResource r) {
        //logger.info("Browser Get from {}", r.uuid());
        //set character encoding...
        HttpServletResponse response = r.getResponse();
        response.setCharacterEncoding("UTF-8");
        //response.setContentType("application/json;charset=UTF-8");

        //login check...
        HttpSession session = r.session();
        if (session == null) {
            logger.info("session expired.");
            outputSessionError(r);
        }
        UserBean ubean = (UserBean)session.getAttribute("userBean");
        if (ubean == null || !ubean.isLoggedIn()) {
            logger.info("login required.");
            outputSessionError(r);
        }
    }

    /**
     * Invoked when the client disconnect or when an unexpected closing of the underlying connection happens.
     *
     * @param event
     */
    @Disconnect
    public void onDisconnect(AtmosphereResourceEvent event) {
        if (event.isCancelled()) {
            logger.info("Browser {} unexpectedly disconnected", event.getResource().uuid());
        } else if (event.isClosedByClient()) {
            logger.info("Browser {} closed the connection", event.getResource().uuid());
        }
    }

}