package es.uv.saic.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
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 org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import es.uv.saic.domain.Wiki;
import es.uv.saic.service.WikiService;

// This class is meant to fill/edit the wiki and wikiEditor html
@Controller
public class WikiController {
	
	@Autowired
	WikiService ws;

	/*
	 * Renders the wiki page
	 * 
	 * @param model The model to pass data to the view
	 * @param auth The authentication object
	 * @return The name of the view to render
	 */
	@GetMapping("/wiki")
	public String renderWiki(Model model, Authentication auth) {
		return "wiki";
	}
	
	/*
	 * Renders the wiki editor page
	 * 
	 * @param model The model to pass data to the view
	 * @param auth The authentication object
	 * @return The name of the view to render
	 */
	@GetMapping("/wiki/editor")
	public String renderWikiEditor(Model model, Authentication auth) {
		return "wikiEditor";
	}
	
	/*
	 * Returns the wiki text for a given category
	 * 
	 * @param model The model to pass data to the view
	 * @param auth The authentication object
	 * @param categoria The category of the wiki
	 * @return The wiki text
	 */
	@GetMapping("/wiki/text/{categoria}")
	@ResponseBody
	public Wiki renderWiki(Model model, Authentication auth, @PathVariable String categoria) {
		return this.ws.findByCategoria(categoria);
	}
	
	/*
	 * Updates the wiki text for a given category
	 * 
	 * @param model The model to pass data to the view
	 * @param auth The authentication object
	 * @param cat The category of the wiki
	 * @param text The new wiki text
	 * @return The updated wiki object
	 */
	@PostMapping("/wiki/editor")
	@ResponseBody
	public Wiki updateWiki(@RequestParam String cat, @RequestParam String text) {
		Wiki w = this.ws.findByCategoria(cat);
		w.setText(text);
		return this.ws.save(w);
	}
	
}
