class PlaylistService extends BasicService implements OwnerAPISupport<Playlist> {

	@POST
	@Path("/playlists/{playlistId}/pagereferences/{pageReferenceId}/moveto/{idx}")
	@Produces(MediaType.APPLICATION_JSON)
	public Playlist movePage(@PathParam("playlistId") long playlistId,
			@PathParam("pageReferenceId") long pageReferenceId, @PathParam("idx") int newPosition) {
		Playlist existingPlaylist = getExistingPlaylist(playlistId, true);

		// find current position
		int newIdx = -1;
		int oldIdx = -1;
		int oldPosition = -1;
		List<PageReference> pageReferences = existingPlaylist.getPageReferences();
		for (int i = 0; i < pageReferences.size(); i++) {
			if (pageReferences.get(i).getId() == pageReferenceId) {
				oldIdx = i;
				oldPosition = pageReferences.get(i).getPosition();
			}
			if (pageReferences.get(i).getPosition() == newPosition) {
				newIdx = i;
			}
		}
		if (oldIdx == newIdx) {
			return existingPlaylist;
		}
		if (oldIdx == -1 || newIdx == -1) {
			throwNotFound();
		}

		// create new list
		List<PageReference> newPageReferences = new ArrayList<>();
		if (oldPosition > newPosition) {
			if (newIdx > 0) {
				newPageReferences.addAll(pageReferences.subList(0, newIdx));
			}
			newPageReferences.add(pageReferences.get(oldIdx));
			pageReferences.remove(oldIdx);
			newPageReferences.addAll(pageReferences.subList(newIdx, pageReferences.size()));
		} else {
			PageReference tmp = pageReferences.get(oldIdx);
			pageReferences.remove(oldIdx);
			if (newIdx > 0) {
				newPageReferences.addAll(pageReferences.subList(0, newIdx));
			}
			newPageReferences.add(tmp);
			newPageReferences.addAll(pageReferences.subList(newIdx, pageReferences.size()));
		}

		// re-index list
		for (int i = 0; i < newPageReferences.size(); i++) {
			newPageReferences.get(i).setPosition(i);
		}
		existingPlaylist.setPageReferences(newPageReferences);

		return PlaylistDAO.save(existingPlaylist);
	}

}