package edu.fiu.controllers;

import edu.fiu.models.User;
import edu.fiu.repositories.UserRepository;
import org.jooby.Err;
import org.jooby.Request;
import org.jooby.Status;
import org.jooby.mvc.*;

import javax.inject.Inject;
import java.util.List;

@Path("api/user")
public class UserController
{

    private UserRepository repo;
    private Request req;

   @Inject
    public UserController(UserRepository repo, Request req) {
        this.repo = repo;
        this.req = req;
    }


    @GET
    public List<User> List () {
        return repo.list();
    }

    @Path(":id")
    public User Get(){
        Integer id = new Integer(req.param("id").intValue());

        User user = repo.get(id);
        if (user == null)
            throw new Err(Status.NOT_FOUND);

        return user;
    }

    @POST
    public User Post() throws Exception {
        User user = req.body(User.class);

        //error
        if(repo.get(user.getName()) != null){
           throw new Err(Status.BAD_REQUEST);
        }

        int id = repo.create(user);
        user.setId(new Integer(id));

        return user;
    }

    @PUT
    public User Put() throws Exception {
        User user = req.body(User.class);

        if(!repo.update(user))
            throw new Err(Status.NOT_FOUND);

        return user;
    }

    @DELETE
    @Path(":id")
    public boolean delete(){
        int id = req.param("id").intValue();

        if(!repo.delete(id)){
            throw new Err(Status.NOT_FOUND);
        }

        return true;
    }
}
