package camp.xit.auth.services.rest.user;

import camp.xit.auth.services.model.UserDetail;
import camp.xit.auth.services.model.UserInfo;
import camp.xit.auth.services.google.GSuiteDirectoryService;
import camp.xit.auth.services.google.model.GroupList;
import camp.xit.auth.services.model.UserDetail.Role;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import org.apache.cxf.rs.security.oidc.common.IdToken;
import org.apache.cxf.rs.security.oidc.rp.OidcClientTokenContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Path("user")
public class UserInfoService {

    private static final String XIT_DOMAIN = "xit.camp";
    private static final Logger log = LoggerFactory.getLogger(UserInfoService.class);
    @Context
    private OidcClientTokenContext oidcContext;
    private final GSuiteDirectoryService directoryService;


    public UserInfoService(GSuiteDirectoryService directoryService) {
        this.directoryService = directoryService;
    }


    @GET
    @Path("info")
    public UserInfo getUserInfo() {
        org.apache.cxf.rs.security.oidc.common.UserInfo userInfo = oidcContext.getUserInfo();
        URI profilePicture = resizeProfilePicture(userInfo.getPicture());
        return new UserInfo(userInfo.getName(), userInfo.getEmail(), profilePicture);
    }


    @GET
    @Path("detail")
    @Produces(MediaType.APPLICATION_JSON)
    public UserDetail getUserDetail() {
        final org.apache.cxf.rs.security.oidc.common.UserInfo userInfo = oidcContext.getUserInfo();
        final IdToken idToken = oidcContext.getIdToken();

        UserDetail detail = new UserDetail();
        detail.setGivenName(userInfo.getGivenName());
        detail.setFamilyName(userInfo.getFamilyName());
        detail.setName(userInfo.getName());
        detail.setEmail(userInfo.getEmail());
        detail.setProfilePicture(resizeProfilePicture(userInfo.getPicture()));
        detail.setEmailVerified(userInfo.getEmailVerified());
        String hdParam = idToken.getStringProperty("hd");
        detail.setRole(XIT_DOMAIN.equals(hdParam) ? Role.INTERNAL : Role.EXTERNAL);
        detail.setSaveGSuitePassword(detail.getRole() == Role.INTERNAL);

        GroupList list = directoryService.getGroups(userInfo.getSubject());
        detail.setGroups(list.getGroups().stream().map(UserDetail.Group::map).collect(Collectors.toList()));

        return detail;
    }


    private URI resizeProfilePicture(String originalUri) {
        return UriBuilder.fromUri(originalUri).queryParam("sz", "100").build();
    }
}

@@ -323,31 +323,8 @@
 RI;%0A
-import java.util.List;%0A
 impo
@@ -2425,24 +2425,68 @@
 Subject());%0A
+        if (list.getGroups() != null) %7B%0A    
         deta
@@ -2582,16 +2582,25 @@
 st()));%0A
+        %7D
 %0A       

Check for NPE