package cz.muni.ics.oidc;

import cz.muni.ics.oidc.server.configurations.PerunOidcConfig;
import cz.muni.ics.oidc.web.controllers.ControllerUtils;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.Map;

public class RedirectUtils {


    private RedirectUtils() {
        // disallow instantiation
    }
    public static void redirectInternal(HttpServletRequest req,
                                        HttpServletResponse res,
                                        PerunOidcConfig config,
                                        String endpoint,
                                        Map<String, Object> sessionParams)
    {
        String redirectUrl = ControllerUtils.createRedirectUrl(config.getBaseURL(), endpoint, Collections.emptyMap());

        HttpSession sess = req.getSession(true);
        for (Map.Entry<String, Object> entry : sessionParams.entrySet()) {
            sess.setAttribute(entry.getKey(), entry.getValue());
        }

        res.reset();
        res.setStatus(HttpServletResponse.SC_FOUND);
        res.setHeader(HttpHeaders.LOCATION, redirectUrl);
    }

    public static void redirectExternal(HttpServletResponse res,
                                        String location)
    {
        res.reset();
        res.setStatus(HttpServletResponse.SC_FOUND);
        res.setHeader(HttpHeaders.LOCATION, location);
    }

}
