package com.pollistics.controllers;

import com.pollistics.models.Poll;
import com.pollistics.services.PollService;
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 org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@Controller
public class PollController {
	@Autowired
	private PollService pollService;

	@GetMapping(value = {"/polls/{pollId}", "/{pollId}"})
	public String greeting(@PathVariable String pollId, Model model) {
		model.addAttribute("poll", pollService.getPoll(pollId));
		return "polls/detail";
	}

	@PostMapping(value = "/polls/create")
	public ModelAndView createPoll(HttpServletRequest request, Model model) {
		String title = request.getParameter("title");
		String option1 = request.getParameter("option1");
		String option2 = request.getParameter("option2");
		String option3 = request.getParameter("option3");
		HashMap<String, Integer> options = new HashMap<>();
		options.put(option1, 0);
		options.put(option2, 0);
		options.put(option3, 0);
		String id = pollService.createPoll(title, options);
		return new ModelAndView("redirect:/" + id);
	}

	@PostMapping(value = "/polls/vote/{pollId}")
	public ModelAndView voteOptions(@PathVariable String pollId, HttpServletRequest request, Model model) {
		String option = request.getParameter("option");
		Poll p = pollService.getPoll(pollId);
		pollService.voteOption(p, option);
		return new ModelAndView("redirect:/" + pollId);
	}
}

@@ -443,61 +443,54 @@
 ng;%0A
+%0A
 import 
-org.springframework.web.servlet.ModelAndView;%0A
+javax.servlet.http.HttpServletRequest;
 %0Aimp
@@ -517,38 +517,40 @@
 tp.HttpServletRe
-quest;
+sponse;%0A
 %0Aimport java.uti
@@ -769,19 +769,168 @@
 el model
-) %7B
+, HttpServletResponse response) %7B%0A%09%09Poll poll = pollService.getPoll(pollId);%0A%09%09if(poll == null) %7B%0A%09%09%09response.setStatus(404);%0A%09%09%09return %22error/404%22;%0A%09%09%7D
 %0A%09%09model
@@ -1057,28 +1057,22 @@
 %09public 
-ModelAndView
+String
  createP
@@ -1520,33 +1520,16 @@
 %09return 
-new ModelAndView(
 %22redirec
@@ -1537,17 +1537,16 @@
 :/%22 + id
-)
 ;%0A%09%7D%0A%0A%09@
@@ -1597,28 +1597,22 @@
 %09public 
-ModelAndView
+String
  voteOpt
@@ -1828,25 +1828,8 @@
 urn 
-new ModelAndView(
 %22red
@@ -1845,16 +1845,15 @@
 + pollId
-)
 ;%0A%09%7D%0A%7D%0A

return 404 for invalid id's