package ovh.herisson.Clyde.EndPoints;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import ovh.herisson.Clyde.Services.AuthenticatorService;
import ovh.herisson.Clyde.Tables.Applications;
import ovh.herisson.Clyde.Tables.Role;
import ovh.herisson.Clyde.Tables.User;

import java.util.ArrayList;

@RestController
@CrossOrigin(originPatterns = "*", allowCredentials = "true")
public class ApplicationsController {

    AuthenticatorService authServ;

    public ApplicationsController(AuthenticatorService authServ){
    this.authServ = authServ;
    }


    /** return a list of authorized applications.
     *  depends on the token
     */
    @GetMapping("/apps")
    public ResponseEntity<Iterable<Applications>> getAuthorizedApps(@RequestHeader("Authorization") String token){
        return new ResponseEntity<>(getAuthorizedApplications(token), HttpStatus.OK);
    }

    @GetMapping("/apps/{identifier}")
    public ResponseEntity<Boolean> getAppAuthorization(@PathVariable Applications identifier, @RequestHeader("Authorization") String token){

        if (getAuthorizedApplications(token).contains(identifier)){
            return new ResponseEntity<>(true, HttpStatus.OK);
        }
        return new ResponseEntity<>(false, HttpStatus.OK);
    }

    public ArrayList<Applications> getAuthorizedApplications(String token){
        ArrayList<Applications> authorizedApps = new ArrayList<>();

        //if unAuthed
        authorizedApps.add(Applications.Login);

		User user = authServ.getUserFromToken(token);
		if(user == null)
            return authorizedApps;
        // if authed
        authorizedApps.add(Applications.Profile);

        if (!authServ.isNotIn(new Role[]{Role.Teacher,Role.Student,Role.Admin},token)) {
            authorizedApps.add(Applications.Msg);
            authorizedApps.add(Applications.Forum);
            authorizedApps.add(Applications.Rdv);
        }

        //if Teacher or Secretary or Admin add ManageCourses App
        if (!authServ.isNotIn(new Role[]{Role.Teacher,Role.Secretary,Role.Admin},token))
            authorizedApps.add(Applications.ManageCourses);

        if (!authServ.isNotIn(new Role[]{Role.InscriptionService,Role.Admin},token)){
            authorizedApps.add(Applications.Inscription);
            authorizedApps.add(Applications.StudentsList);}

        if (!authServ.isNotIn(new Role[]{Role.Secretary,Role.Admin},token)){ 
          authorizedApps.add(Applications.UsersList);}
        return authorizedApps;
    }
}
