package de.jottyfan.camporganizer.module.confirmation.board;

import java.io.IOException;
import java.security.Principal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

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.PathVariable;

import de.jottyfan.camporganizer.module.camplist.CommonController;
import jakarta.servlet.http.HttpServletResponse;

/**
 *
 * @author jotty
 *
 */
@Controller
public class ConfirmationBoardController extends CommonController {

	@Autowired
	private ConfirmationBoardService service;

	@GetMapping("/confirmation/board")
	public String getBoard(Model model, Principal principal) {
		model.addAttribute("camps", service.loadCampList(super.getCurrentUser(principal)));
		return "/confirmation/board";
	}

	@GetMapping("/confirmation/board/camp/{id}")
	public String getCamplist(Model model, @PathVariable("id") Integer id, Principal principal) {
		model.addAttribute("campId", id);
		model.addAttribute("campStartDate", service.getCampStartDate(super.getCurrentUser(principal), id));
		model.addAttribute("persons", service.loadPersonList(super.getCurrentUser(principal), id));
		return "/confirmation/camplist";
	}

	@GetMapping("/confirmation/board/download/{id}")
	public void getCsvOfAll(@PathVariable("id") Integer id, Principal principal, HttpServletResponse response)
			throws IOException {
		response.setContentType("text/csv");
		String filename = String.format("camplist_%d_%s.csv", id,
				LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")));
		response.setHeader("Content-Disposition", "attachment; filename=" + filename);
		response.getWriter().write(service.getDownloadCsvOfAll(super.getCurrentUser(principal), id));
		response.flushBuffer();
	}
}
