package com.controller;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.bean.RecaptchaBean;
import com.util.CaptchaValidator;

@Controller
public class SpringMVCController {
	
	@Autowired
	private CaptchaValidator captchaValidator;
	
	
	@RequestMapping(value="/helloWorld.web",method = RequestMethod.GET)
	public String printWelcome(ModelMap model) {
 
		model.addAttribute("message", "Google Recaptcha!!!");
		model.addAttribute("captchajs", captchaValidator.getCaptchajs());
		model.addAttribute("captchaPublicKey", captchaValidator.getCaptchaPublicKey());		
		return "helloWorld";
 
	}
	
	@RequestMapping(value="/submitCaptcha.web",method = RequestMethod.POST)
	public String submitCaptcha(@ModelAttribute("recaptchaBean") RecaptchaBean recaptchaBean,BindingResult result, ModelMap model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
 
		String captchaChallenge = request.getParameter("recaptcha_challenge_field");
		String captchaText = request.getParameter("recaptcha_response_field");		
		List<String> captchErrors = captchaValidator.validate(captchaChallenge, captchaText);			
		if (!captchErrors.isEmpty()){
			recaptchaBean.setCaptchaError(captchErrors.get(0));	
			result.rejectValue("captchaError", captchErrors.get(0));
			model.addAttribute("message", "Google Recaptcha!!!");
			model.addAttribute("captchajs", captchaValidator.getCaptchajs());
			model.addAttribute("captchaPublicKey", captchaValidator.getCaptchaPublicKey());
			return "helloWorld";
		}else {
			model.addAttribute("captchaValue", captchaText);
			model.addAttribute("message", "Successful!!!");
			return "captchaValidateSuccessful";
		}		
		
	}
	
	
}
	
