package ch.zuehlke.campplanner.controller;

import ch.zuehlke.campplanner.dao.RatingRepository;
import ch.zuehlke.campplanner.domain.Hotel;
import ch.zuehlke.campplanner.domain.Rating;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/rest/hotels/{hotelId}/ratings")
public class HotelRatingController {
	@Autowired
	private RatingRepository ratingRepository;

	@Transactional
	@RequestMapping(method = RequestMethod.GET)
	public List<Rating> getAll(@PathVariable("hotelId") long hotelId) {
		return ratingRepository.findByHotelId(hotelId);
	}

	@Transactional
	@RequestMapping(method = RequestMethod.POST)
	public ResponseEntity<Rating> addOrUpdate(@PathVariable("hotelId") long hotelId, @RequestBody Rating rating) {
		if (rating.getRatingFrom1To5() == null) {
			return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
		}
		Hotel hotel = new Hotel();
		hotel.setId(hotelId);
		rating.setDate(new Date());
		rating.setHotel(hotel);
		ratingRepository.save(rating);
		return new ResponseEntity<>(rating, HttpStatus.OK);
	}
}

@@ -333,16 +333,145 @@
 Entity;%0A
+import org.springframework.security.core.Authentication;%0Aimport org.springframework.security.core.context.SecurityContextHolder;%0A
 import o
@@ -1356,16 +1356,51 @@
 hotel);%0A
+%09%09rating.setPerson(getUserName());%0A
 %09%09rating
@@ -1480,11 +1480,289 @@
 .OK);%0A%09%7D
+%0A%0A%09private String getUserName() %7B%0A%09%09Authentication auth = SecurityContextHolder.getContext().getAuthentication();%0A%09%09if (auth == null) %7B%0A%09%09%09// Should not happen, except in development, when user doesn't has to be authenticated%0A%09%09%09return %22unknown%22;%0A%09%09%7D%0A%09%09return auth.getName();%0A%09%7D
 %0A%7D%0A

add username to rating on creation