package com.atlassian.stash.sal.api.web.context;

import com.atlassian.sal.api.web.context.HttpContext;
import com.atlassian.bitbucket.request.RequestContext;
import com.atlassian.bitbucket.request.RequestManager;

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

/**
 * Implementation of {@link HttpContext} for Stash.
 *
 * @since 2.1
 */
public class DefaultHttpContext implements HttpContext {

    private final RequestManager requestManager;

    public DefaultHttpContext(RequestManager requestManager) {
        this.requestManager = requestManager;
    }

    @Override
    public HttpServletRequest getRequest() {
        RequestContext context = requestManager.getRequestContext();
        if (context != null && context.getRawRequest() instanceof HttpServletRequest) {
            return (HttpServletRequest) context.getRawRequest();
        }

        return null;
    }

    @Override
    public HttpServletResponse getResponse() {
        RequestContext context = requestManager.getRequestContext();
        if (context != null && context.getRawResponse() instanceof HttpServletResponse) {
            return (HttpServletResponse) context.getRawResponse();
        }

        return null;
    }

    @Override
    public HttpSession getSession(boolean b) {
        HttpServletRequest request = getRequest();
        return request != null ? request.getSession(b) : null;
    }
}
