Skip to content
Snippets Groups Projects
TrainerRoute.java 1.71 KiB
Newer Older
package nl.utwente.mod4.pokemon.routes;

import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import nl.utwente.mod4.pokemon.dao.TrainerDao;
import nl.utwente.mod4.pokemon.model.ResourceCollection;
import nl.utwente.mod4.pokemon.model.Trainer;

@Path("/trainers")
public class TrainerRoute {


    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public ResourceCollection<Trainer> getTrainers(
            @QueryParam("pageSize") int pageSize,
            @QueryParam("pageNumber") int pageNumber
    ) {
        int ps = pageSize > 0 ? pageSize : Integer.MAX_VALUE;
        int pn = pageNumber > 0 ? pageNumber : 1;
        var resources = TrainerDao.INSTANCE.getTrainers(ps, pn).toArray(new Trainer[0]);
        var total = TrainerDao.INSTANCE.getTotalTrainers();

        return new ResourceCollection<>(resources, ps, pn, total);
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Trainer createTrainer(Trainer pokemonType) {
        return TrainerDao.INSTANCE.create(pokemonType);
    }

    @GET
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Trainer getTrainer(@PathParam("id") String id) {
        return TrainerDao.INSTANCE.getTrainer(id);
    }

    @PUT
    @Path("/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public Trainer updateTrainer(@PathParam("id") String id, Trainer toUpdate) {
        if (id == null || !id.equals(toUpdate.id))
            throw new BadRequestException("Id mismatch.");

        return TrainerDao.INSTANCE.update(toUpdate);
    }

    @DELETE
    @Path("/{id}")
    public void deleteTrainer(@PathParam("id") String id) {
        TrainerDao.INSTANCE.delete(id);
    }
}