package controllers;
import be.objectify.deadbolt.java.actions.Group;
import be.objectify.deadbolt.java.actions.Restrict;
import com.fasterxml.jackson.databind.ObjectMapper;
import dao.DataAccessException;
import models.DaoManager;
import models.dto.ContactsListDTO;
import models.dto.UserDto;
import models.dto.UsersListDto;
import models.dto.UsersListItemDto;
import models.entities.Contact;
import models.entities.User;
import models.entities.UserRole;
import play.Logger;
import play.db.jpa.Transactional;
import play.mvc.Controller;
import play.mvc.Result;
import utils.Utilities;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.List;
import static play.libs.Json.toJson;
/**
* Created by kiryl on 18.08.2014.
*/
@Restrict({@Group("admin")})
public class UserController extends Controller {
@Transactional
@Restrict({@Group("manager"), @Group("admin"), @Group("supervisor")})
public static Result getUser(Integer id) {
try {
User user = DaoManager.getUserDao().findById(id);
if (user == null) {
return notFound("Can't find user with id " + id);
}
UserDto userDto = UserDto.createFrom(user);
return ok(toJson(userDto));
} catch (DataAccessException e) {
Logger.error("Can't find user with id " + id, e);
return notFound("Can't find user with id " + id);
}
}
@Transactional
public static Result list(Integer pageNumber, Integer pageSize) {
if (pageNumber == null || pageSize == null || pageNumber <= 0 || pageNumber <= 0) {
return badRequest(Utilities.getJsonErrorNode("Bad page number or size"));
}
try {
List<User> users = DaoManager.getUserDao().getBatch(pageNumber - 1, pageSize);
Integer totalUsers = DaoManager.getUserDao().totalEntities();
Integer totalPages = Double.valueOf(Math.ceil((double) totalUsers / pageSize)).intValue();
UsersListDto usersDto = UsersListDto.createFrom(users, totalPages);
return ok(toJson(usersDto));
} catch (DataAccessException e) {
Logger.error("Failed to get a batch of users. Page: " + pageNumber + ", size: " + pageSize, e);
return notFound("Can't get page " + pageNumber + ", size: " + pageSize);
}
}
@Transactional
@Restrict({@Group("manager"), @Group("admin"), @Group("supervisor")})
public static Result quickSearchUsers(Integer pageNumber, Integer pageSize, String role, String term) {
if (pageNumber == null || pageSize == null || pageNumber <= 0 || pageNumber <= 0) {
Logger.error("Illegal page number or size");
return badRequest(Utilities.getJsonErrorNode("Illegal page number or size"));
}
try {
List<User> users = DaoManager.getUserDao().quickSearch(pageNumber - 1, pageSize, role, term);
if (users.size() == 0) {
return notFound("No one user suits search parameters");
}
Integer totalUsers = DaoManager.getUserDao().quickSearchResultsCount(role, term);
Integer totalPages = Double.valueOf(Math.ceil((double) totalUsers / pageSize)).intValue();
UsersListDto listDTO = UsersListDto.createFrom(users, totalPages);
return ok(toJson(listDTO));
} catch (DataAccessException e) {
Logger.error("Failed to get a batch of users. Page: " + pageNumber, e);
return notFound("Can't get page " + pageNumber);
}
}
@Transactional
@Restrict({@Group("manager"), @Group("admin"), @Group("supervisor"), @Group("executor"), @Group("delivery-manager")})
public static Result getByRole(String roleName) {
try {
UserRole role = DaoManager.getUserRoleDao().findByName(roleName);
if (role == null) {
return notFound("Can't find role " + roleName);
}
List<User> users = DaoManager.getUserDao().findByRole(role);
UsersListDto usersDto = UsersListDto.createFrom(users, 1);
return ok(toJson(usersDto));
} catch (DataAccessException e) {
Logger.error("Can't find users with role " + roleName, e);
return notFound("Can't find users with role " + roleName);
}
}
@Transactional
public static Result addNew() {
try {
Logger.debug("add req body: " + request().body().asJson().toString());
UserDto userDto = new ObjectMapper().readValue(request().body().asJson().toString(), UserDto.class);
User newUser = new User();
userDto.mapBack(newUser);
ConstraintViolation[] violations = Utilities.validateEntity(newUser);
if (violations.length > 0) {
return badRequest(Utilities.violationsToJson(violations));
}
DaoManager.getUserDao().persist(newUser);
} catch (IOException e) {
Logger.error("Failed to parse new user json", e);
return badRequest(Utilities.getJsonErrorNode("Failed to parse new user json"));
} catch (DataAccessException e) {
Logger.error("Failed to save new user", e);
return badRequest(Utilities.getJsonErrorNode("Failed to save new user"));
}
return ok();
}
@Transactional
public static Result update(int userId) {
try {
User user = DaoManager.getUserDao().findById(userId);
if (user == null) {
return notFound(Utilities.getJsonErrorNode("Can't find user with id " + userId));
}
Logger.debug("update req body: " + request().body().asJson().toString());
UserDto userDto = new ObjectMapper().readValue(request().body().asJson().toString(), UserDto.class);
userDto.mapBack(user);
ConstraintViolation[] violations = Utilities.validateEntity(user);
if (violations.length > 0) {
return badRequest(Utilities.violationsToJson(violations));
}
DaoManager.getUserDao().persist(user);
} catch (IOException e) {
Logger.error("Failed to parse updated user json", e);
return badRequest(Utilities.getJsonErrorNode("Failed to parse updated user json"));
} catch (DataAccessException e) {
Logger.error("Failed to save updated user", e);
return badRequest(Utilities.getJsonErrorNode("Failed to save updated user"));
}
return ok("saved updated user");
}
@Transactional
public static Result remove(int userId) {
try {
User user = DaoManager.getUserDao().findById(userId);
if (user == null) {
return notFound(Utilities.getJsonErrorNode("Can't find user with id " + userId));
}
DaoManager.getUserDao().remove(user);
} catch (DataAccessException e) {
Logger.error("Failed to remove user " + userId, e);
return badRequest(Utilities.getJsonErrorNode("Failed to remove user " + userId));
}
return ok("removed user " + userId);
}
@Transactional
public static Result removeBatch() {
try {
Integer[] selectedIds = new ObjectMapper().readValue(request().body().asJson().toString(), Integer[].class);
for (Integer id : selectedIds) {
remove(id);
}
return ok();
} catch (IOException e) {
return badRequest(Utilities.getJsonErrorNode("Failed to parse array of ids"));
}
}
}