package com.fusi24.hse.begems.editor.controller;

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.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.fusi24.hse.begems.editor.model.BegemsDocumentContent;
import com.fusi24.hse.begems.editor.model.BegemsDocumentContentRepo;

@Controller
public class WebController {

	@Autowired
	private BegemsDocumentContentRepo begemsDocumentContentRepo;
	
	@GetMapping
	public ModelAndView index(@RequestParam String key) {
		BegemsDocumentContent documentContent = begemsDocumentContentRepo.findFirstByGeneratedId(key).orElse(null);
		if(documentContent == null) throw new RuntimeException("Key is required.");
		ModelAndView modelAndView = new ModelAndView("index");
		modelAndView.addObject("title", "HSE Editor");
		modelAndView.addObject("heading", "HSE BeGeMS Document Editor");
		modelAndView.addObject("documentContent", documentContent);
		modelAndView.addObject("content", documentContent.getValue());
		return modelAndView;
	}
	
	@PostMapping
	public String saveContent(Model model, @ModelAttribute BegemsDocumentContent data) {
		begemsDocumentContentRepo.save(data);
		return "redirect:/?key="+data.getGeneratedId();
	}
}
