package de.jottyfan.camporganizer.module.business.bookings;

import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import de.jottyfan.camporganizer.module.business.bookings.impl.AddPaymentBean;
import de.jottyfan.camporganizer.module.business.bookings.impl.BookerBean;
import de.jottyfan.camporganizer.module.business.business.IBusinessService;

/**
*
* @author jotty
*
*/
@Controller
public class BookingsController {
	private static final Logger LOGGER = LogManager.getLogger(BookingsController.class);

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private IBusinessService indexService;

	@Autowired
	private IBookingsService bookingsService;

	@GetMapping("/business/bookings")
	@RolesAllowed({"business_booking"})
	public String getBookings(Model model) {
		String username = indexService.getCurrentUser(request);
		model.addAttribute("currentUser", username);
		model.addAttribute("bookers", bookingsService.getBookers(username));
		model.addAttribute("addBean", new AddPaymentBean());
		return "business/bookings";
	}

	@GetMapping("/business/bookings/{id}")
	@RolesAllowed({"business_booking"})
	public String getBooking(Model model, @PathVariable Integer id) {
		String username = indexService.getCurrentUser(request);
		model.addAttribute("currentUser", username);
		BookerBean bean = bookingsService.getBooker(id, username);
		model.addAttribute("booker", bean);
		model.addAttribute("addBean", new AddPaymentBean());
		return bean == null ? getBookings(model) : "business/booker";
	}

	@PostMapping("/business/bookings/payment/{id}")
	@RolesAllowed({"business_booking"})
	public String addPayment(Model model, @ModelAttribute AddPaymentBean bean, @PathVariable Integer id) {
		Double payment = bean.getPayment();
		bookingsService.addPayment(id, payment);
		return getBooking(model, id);
	}

	@PostMapping("/business/bookings/listpayment/{id}")
	@RolesAllowed({"business_booking"})
	public String addListPayment(Model model, @ModelAttribute AddPaymentBean bean, @PathVariable Integer id, @RequestParam(defaultValue = "") String search) {
		Double payment = bean.getPayment();
		bookingsService.addPayment(id, payment);
		LOGGER.debug("search is {}", search);
		model.addAttribute("search", search);
		return getBookings(model);
	}
}
