package org.helianto.security.controller;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.helianto.core.domain.Signup;
import org.helianto.core.sender.UserConfirmationSender;
import org.helianto.security.service.SignupService;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;


/**
 * Base classe to SignUpController.
 * 
 * @author mauriciofernandesdecastro
 */
@Controller
@RequestMapping(value="/signup")
public class SignUpController 
	extends AbstractCryptoController
{

	public static final String SIGN_UP = "/signup/";
	
	public static final String SIGN_UP_TEMPLATE = "security/signup";
	
	public static final String WELCOME_TEMPLATE = "security/welcome";
	
	@Inject
	private Environment env;
	
	@Inject
	private SignupService signupService;

	@Inject 
	private UserConfirmationSender userConfirmationSender;
	
	/**
	 * Send user confirmation e-mail.
	 * 
	 * @param signup
	 */
	public String sendConfirmation(Signup signup) {
		if (userConfirmationSender.send(signup.getPrincipal(), signup.getFirstName(), signup.getLastName(), "Email Confirmação", "confirmationToken", signup.getToken())) {
			return "true";
		}
		return "false";
	}
	
	/**
	 * Signup request.
	 * 
	 * @param model
	 * @param contextId
	 * @param principal
	 * @param request
	 */
	@RequestMapping(value={"/", ""}, method=RequestMethod.GET)
	public ModelAndView getSignupPage(Model model, @RequestParam(defaultValue="1") Integer contextId
			, @RequestParam(required=false) String principal, WebRequest request) {
		if(signupService.notifyAdminIfUserIsNotValid(contextId, principal)){
			return new ModelAndView("forward:/");
		}
		Signup signup = signupService.socialSignUpAttempt(contextId, request);
		return new ModelAndView(SIGN_UP_TEMPLATE, "form", signup);
	}
	
	/**
	 * Save the lead.
	 * 
	 * @param model
	 * @param principal
	 */
	@RequestMapping(value={"/", ""}, method=RequestMethod.GET, params="tempEmail", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public String saveLead(@RequestParam String principal) {
		if(signupService.saveLead(principal)){
			return "{\"exists\": true}";
		}
		return "{\"exists\": false}";
	}
	

	/**
	 * Check if email exists.
	 * 
	 */
	@RequestMapping(value={"/", ""}, method=RequestMethod.POST, params="emailChecked", produces = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public String checkMail(@RequestBody Signup form) {
		return "{\"notExists\":" + signupService.searchPrincipal(form) + "}";
	}
	
	/**
	 * Signup submission
	 * 
	 * @param model
	 * @param signup
	 * @param error
	 * @param request
	 */
	@RequestMapping(value={"/", ""}, method= RequestMethod.POST)
	public String postSignupPage(Model model, @Valid Signup signup, BindingResult error, HttpServletRequest request) {
		String ipAddress = request.getHeader("X-FORWARDED-FOR");  
		if (ipAddress == null) {  
			  ipAddress = request.getRemoteAddr();  
		}
		// TODO prevent double submission
		signup.setToken(signupService.createToken());
		signup = signupService.saveSignup(signup, ipAddress);
		boolean userExists = signupService.allUsersForIdentityAreValid(signup);
		model.addAttribute("userExists", userExists);

		if (userExists) {
			model.addAttribute("sender", env.getProperty("iservport.sender.mail"));
			model.addAttribute("emailSent", sendConfirmation(signup));
		}
		model.addAllAttributes(signup.createMapFromForm());
		return WELCOME_TEMPLATE;
	}
	
	// TODO
	public void resendConfirmation() {
		
	}
	
}

@@ -1187,17 +1187,16 @@
 %22/signup
-/
 %22;%0A%09%0A%09pu
@@ -1595,24 +1595,83 @@
 p signup) %7B%0A
+%09%09System.err.println(%22Signup: %22 + signup.getPrincipal());%0A%0A
 %09%09if (userCo
@@ -2483,21 +2483,29 @@
 %09 * 
-Save the lead
+Check if email exists
 .%0A%09 
@@ -2609,16 +2609,365 @@
 hod.GET,
+ params=%22principal%22, produces = MediaType.APPLICATION_JSON_VALUE)%0A%09@ResponseBody%0A%09public String verify(@RequestParam String principal) %7B%0A%09%09return %22%7B%5C%22exists%5C%22:%22 + !signupService.searchPrincipal(new Signup(0, principal)) + %22%7D%22;%0A%09%7D%0A%09%0A%09/**%0A%09 * Save Lead%0A%09 * @param principal%0A%09 * @return%0A%09 */%0A%09@RequestMapping(value=%7B%22/%22, %22%22%7D, method=RequestMethod.POST,
  params=
@@ -3080,32 +3080,32 @@
 aram String 
-principa
+tempEmai
 l) %7B%0A%09%09if(si
@@ -3125,24 +3125,24 @@
 aveLead(
-principa
+tempEmai
 l))%7B%0A%09%09%09

Check if e-mail exists.