package cz.muni.ics.oidc.web.controllers;

import cz.muni.ics.oidc.server.configurations.PerunOidcConfig;
import cz.muni.ics.oidc.web.WebHtmlClasses;
import cz.muni.ics.openid.connect.view.HttpCodeView;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

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

/**
 *  Controller for IS TEST SP pages.
 *
 * @author Pavol Pluta <pavol.pluta1@gmail.com>
 */
@Controller
@Slf4j
public class TestSpWarningController {

    public static final String MAPPING = "/testSp";
    public static final String SESS_ATTR_TARGET = "target";
    public static final String SESS_ATTR_IS_TEST_SP_APPROVED = "isTestSpApprovedSession";

    private final WebHtmlClasses htmlClasses;
    private final PerunOidcConfig perunOidcConfig;

    @Autowired
    public TestSpWarningController(WebHtmlClasses htmlClasses, PerunOidcConfig perunOidcConfig) {
        this.htmlClasses = htmlClasses;
        this.perunOidcConfig = perunOidcConfig;
    }

    @GetMapping(value = MAPPING)
    public String showTestSpWarning(HttpServletRequest req,
                                    Map<String, Object> model)
    {
        ControllerUtils.setPageOptions(model, req, htmlClasses, perunOidcConfig);
        return "test_rp_warning";
    }

    @PostMapping(value = MAPPING)
    public String showTestSpWarningSubmit(HttpSession sess, Map<String, Object> model)
    {
        if (sess != null) {
            sess.setAttribute(SESS_ATTR_IS_TEST_SP_APPROVED, true);
            String target = (String) sess.getAttribute(SESS_ATTR_TARGET);
            if (target != null) {
                return "redirect:" + target;
            }
        }
        log.debug("showTestSpWarningSubmit: missing session attribute TARGET, cannot redirect to original req");
        model.put(HttpCodeView.CODE, HttpStatus.INTERNAL_SERVER_ERROR);
        return HttpCodeView.VIEWNAME;

    }

}
