package com.pas.controller;

import java.util.Map;

import javax.validation.Valid;
import javax.ws.rs.core.MediaType;

import org.codehaus.jackson.jaxrs.JacksonJsonProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
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.servlet.ModelAndView;

import com.pas.beans.Constants;
import com.pas.model.User;
import com.pas.service.UserService;
import com.pas.service.UserTypeService;
import com.pas.web.UserForm;
import com.pas.web.ValidadorUserForm;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

@Controller
@RequestMapping(value = "/user")
public class UserController {
	
	@Autowired
	UserService userService;

	@Autowired
	UserTypeService userTypeservice;
	
	@InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new ValidadorUserForm()); // registramos el validador
    }
	
	@RequestMapping("/myPage")
	public String myPage(Map<String, Object> map) {
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String name = auth.getName();
		
		map.put("name", name);
		
		return "userScreen";
	}

	@RequestMapping("/register")
	public ModelAndView registerUser() {
		
		ModelMap model = new ModelMap();
		model.addAttribute("userForm", new UserForm());
		
		return new ModelAndView("registerForm", model);
	}

	@RequestMapping(value="/create", method = RequestMethod.POST)
	public ModelAndView createUser(@ModelAttribute("userForm") @Valid UserForm userForm, 
            BindingResult result) {

		ModelAndView mav = new ModelAndView();
		ClientConfig clientConfig = new DefaultClientConfig();
		clientConfig.getClasses().add(JacksonJsonProvider.class);
		Client client = Client.create(clientConfig);

		 if ( !result.hasErrors() ) {
			// si no hay errores tratamos los datos
			// se obtiene el valor del tipo de usuario por defecto
//			String idUserType = Utils.getIdUserTypeByName("User");
//			userForm.setUserType((idUserType.length()>0 ? idUserType : "2"));
			userForm.setUserType("2");
			
			
			ClientResponse response = client
					.resource(Constants.userController_WSURL+"/create")
					.type(MediaType.APPLICATION_JSON)
					.accept(MediaType.APPLICATION_JSON)
					.entity(userForm)
					.post(ClientResponse.class, userForm);

			//Pantalla y mensaje de retorno
			mav.setViewName("welcome");
			if (response.getStatus() != 200) {
				mav.addObject("mesage", "Código de error HTTP : " + response.getStatus());
			} else {
				mav.addObject("mesage", "Felicidades " + userForm.getName() + " ya eres un usuario de ParkandSave!!");
			}
		}else{
			// si hay errores volvemos a la vista del formulario
			mav.addObject("user", userForm);
			mav.setViewName("registerForm");
		}
		
		return mav;
    }

	@RequestMapping(value="/modify", method = RequestMethod.POST)
	public String modifyUser(@RequestParam("id") String id, @RequestParam("name") String name, 
			@RequestParam("lastname") String lastname, @RequestParam("username") String username, 
			@RequestParam("pwd") String pwd, @RequestParam("email") String email, 
			@RequestParam("usertype") String usertype) {
		
		return "welcome";
	}
	
	@RequestMapping(value="/changePwd", method = RequestMethod.POST)
	public ModelAndView pageWelcome(@RequestParam("id") String id, 
			@RequestParam("pwdN") String pwdN, @RequestParam("pwdO") String pwdO) {
		
		return new ModelAndView("welcome", "message", "Bienvenidos a Park&Save!!");
	}
}