package eu.eudat.controllers;

import eu.eudat.logic.security.CustomAuthenticationProvider;
import eu.eudat.logic.security.validators.TokenValidatorFactoryImpl;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.login.LoginInfo;
import eu.eudat.models.data.principal.PrincipalModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
@RequestMapping(value = {"/api/auth/saml2"})
public class Saml2PostBinding extends BaseController {

    private CustomAuthenticationProvider customAuthenticationProvider;

    @Autowired
    public Saml2PostBinding(ApiContext apiContext, CustomAuthenticationProvider customAuthenticationProvider) {
        super(apiContext);
        this.customAuthenticationProvider = customAuthenticationProvider;
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/postBinding"}, consumes = "application/x-www-form-urlencoded")
    public @ResponseBody
    ResponseEntity<Void> verify(@RequestParam(value = "SAMLResponse") String SAMLResponse, @RequestParam(value = "RelayState") String RelayState) throws GeneralSecurityException {

        Map<String, String> map = Arrays.stream(RelayState.split("&")).map(s -> s.split("=")).collect(Collectors.toMap(e -> e[0], e -> e[1]));

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setTicket(SAMLResponse);
        loginInfo.setProvider(TokenValidatorFactoryImpl.LoginProvider.CONFIGURABLE.getValue());
        Map<String, String> providerId = new HashMap<>();
        providerId.put("configurableLoginId", map.get("configurableLoginId"));
        loginInfo.setData(providerId);

        PrincipalModel principal = this.customAuthenticationProvider.authenticate(loginInfo);

        return ResponseEntity.status(HttpStatus.FOUND).header(HttpHeaders.LOCATION, "http://localhost:4200/login/external/saml?token=" + principal.getToken().toString()).build();

    }

}
