package uk.ac.ebi.subs.api.controllers;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.rest.webmvc.BasePathAwareController;
import org.springframework.data.rest.webmvc.ResourceNotFoundException;
import org.springframework.data.web.PagedResourcesAssembler;
import org.springframework.hateoas.Resource;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import uk.ac.ebi.subs.data.component.Team;
import uk.ac.ebi.subs.repository.repos.SubmissionRepository;
import uk.ac.ebi.subs.repository.model.Submission;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;

@RestController
@BasePathAwareController
public class TeamController {

    public TeamController(SubmissionRepository submissionRepository, PagedResourcesAssembler<Submission> pagedResourcesAssembler) {
        this.submissionRepository = submissionRepository;
        this.pagedResourcesAssembler = pagedResourcesAssembler;
    }

    private SubmissionRepository submissionRepository;
    private PagedResourcesAssembler<Submission> pagedResourcesAssembler;

    @RequestMapping("/teams/{teamName}")
    public Resource<Team> getTeam(@PathVariable String teamName) {
        //TODO this is a stub, we should make sure that the Teams are real and that the user is authorised
        Team d = new Team();
        d.setName(teamName);

        Page<Submission> subsPage = submissionRepository.findByTeamName(teamName, new PageRequest(0, 1));

        if (subsPage.getTotalElements() == 0) {
            throw new ResourceNotFoundException();
            //TODO temporary check until we have real team support
        }

        Resource<Team> resource = new Resource<>(d);

        resource.add(
                linkTo(
                        methodOn(this.getClass()).getTeam(
                                d.getName()
                        )
                ).withSelfRel()
        );

        return resource;
    }

}

@@ -377,16 +377,69 @@
 source;%0A
+import org.springframework.security.access.method.P;%0A
 import o
@@ -772,16 +772,85 @@
 mission;
+%0Aimport uk.ac.ebi.subs.repository.security.PreAuthorizeParamTeamName;
 %0A%0Aimport
@@ -1501,16 +1501,47 @@
 Name%7D%22)%0A
+    @PreAuthorizeParamTeamName%0A
     publ
@@ -1579,16 +1579,31 @@
 Variable
+ @P(%22teamName%22)
  String 

secure team controller