package ovh.herisson.Clyde.EndPoints;


import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ovh.herisson.Clyde.Responses.UnauthorizedResponse;
import ovh.herisson.Clyde.Services.AuthenticatorService;
import ovh.herisson.Clyde.Services.CurriculumCourseService;
import ovh.herisson.Clyde.Services.CurriculumService;
import ovh.herisson.Clyde.Tables.Curriculum;
import ovh.herisson.Clyde.Tables.Role;

import java.util.Map;

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


    private final CurriculumService curriculumServ;
    private final AuthenticatorService authServ;

    private final CurriculumCourseService curriculumCourseServ;

    public CurriculumController(CurriculumService curriculumServ, AuthenticatorService authServ, CurriculumCourseService curriculumCourseServ){
        this.curriculumServ = curriculumServ;
        this.authServ = authServ;
        this.curriculumCourseServ = curriculumCourseServ;
    }

    @GetMapping("/curriculum/{id}")
    public ResponseEntity<Map<String,Object>> findById(@PathVariable long id){
        Curriculum foundCurriculum = curriculumServ.findById(id);

        if (foundCurriculum == null)
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

        return new ResponseEntity<>(curriculumCourseServ.getDepthCurriculum(foundCurriculum), HttpStatus.OK);
    }

    @GetMapping("/curriculums")
    public ResponseEntity<Iterable<Map<String, Object>>> findAllIndDepth(){
        return new ResponseEntity<>(curriculumCourseServ.getAllDepthCurriculum(),HttpStatus.OK);
    }

    @PostMapping("/curriculum")
    public ResponseEntity<Curriculum> postCurriculum(@RequestHeader("Authorization") String token,@RequestBody Curriculum curriculum){

        if (authServ.isNotIn(new Role[]{Role.Secretary,Role.Admin},token))
            return new UnauthorizedResponse<>(null);

        return new ResponseEntity<>(curriculumServ.save(curriculum),HttpStatus.CREATED);
    }

    @PostMapping("/curriculum/{id}")
    public ResponseEntity<String> postCoursesToCurriculum(@RequestHeader("Authorization") String token,
                                                          @RequestBody Iterable<Long> coursesIds,
                                                          @PathVariable long id)
    {

        if (authServ.isNotIn(new Role[]{Role.Admin,Role.Secretary},token))
            return new UnauthorizedResponse<>(null);

        if (!curriculumCourseServ.saveAll(coursesIds, curriculumServ.findById(id)))
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);

        return new ResponseEntity<>(HttpStatus.OK);
    }
}
