package es.uv.saic.web;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.Optional;

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.DeleteMapping;
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.shared.domain.Calendari;
import es.uv.saic.shared.domain.Usuari;
import es.uv.saic.shared.feign.CalendarClient;

@Controller
public class CalendarController {

    @Autowired
    private CalendarClient cc;

    @ResponseBody
	@PostMapping("/calendar")
	public Calendari calendarAddEvent(Model model, Authentication auth, @RequestParam("idProces") Integer idProces, 
			@RequestParam("titulacions") List<String> titulacions, @RequestParam("centres") List<String> centres, 
			@RequestParam("data") String data, @RequestParam("instancia") Optional<Integer> instancia) throws IOException, ParseException {	
		
		return cc.calendarAddEvent(idProces, titulacions, centres, data, instancia);
	}
	
	// POST que actualiza el evento ddel calendario
	@ResponseBody
	@PostMapping("/calendar/{id}")
	public Calendari calendarAddEvent(Model model, Authentication auth, @PathVariable("id") Integer id, 
			@RequestParam("idProces") Integer idProces, @RequestParam("titulacions") List<String> titulacions, 
			@RequestParam("centres") List<String> centres, @RequestParam("data") String data) throws IOException, ParseException {	
		return cc.calendarAddEvent(id, idProces, titulacions, centres, data);
	}
	
	// GET que recoge todos los eventos del calendario
	@ResponseBody
	@GetMapping("/calendar")
	public List<Calendari> calendarGetEvents(Model model, Authentication auth) throws IOException, ParseException {	
		return cc.calendarGetEvents();
	}
	
	// DELETE que elimina un evento del calendario
	@ResponseBody
	@DeleteMapping("/calendar")
	public Integer calendarDeleteEvent(Model model, Authentication auth, @RequestParam("id") Integer id) throws IOException, ParseException {	
		return cc.calendarDeleteEvent(id);
	}
	

	// POST para instanciar un proceso desde el calendario
	@ResponseBody
	@PostMapping("/calendar/instantiate")
	public List<String> instantiate(Model model, Authentication auth, @RequestParam("id") Integer id,
			@RequestParam("idProces") Integer idProces, @RequestParam("centres") List<Integer> centres,
			@RequestParam("titulacions") List<Integer> titulacions) throws IOException, ParseException {	
		return cc.instantiate(id, idProces, centres, titulacions, ((Usuari) auth.getPrincipal()).getUsuari());
	}
}
