package org.artgasmator.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class UserController {
	
	@Autowired
	private UserDetailsManager userDetailsManager;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Autowired
	private SaltSource saltSource;
	
	@RequestMapping(value="/login", method=RequestMethod.POST)
	public String createUser(@RequestParam("user")String username, 
				@RequestParam("password") String password,
				Model model) {
		
		if (!userDetailsManager.userExists(username)) {
		
			List<GrantedAuthority> authorites = new ArrayList<GrantedAuthority>();
			authorites.add(new GrantedAuthorityImpl("ROLE_USER"));
			
			
			User user = new User(username, password, true, false, false, false, authorites);
			User saltedUser = new User(username, passwordEncoder.encodePassword(password, saltSource.getSalt(user)), 
					true, false, false, false, authorites);
			
			userDetailsManager.createUser(saltedUser);
			
		}
		return "login";
	}
	
	@RequestMapping(value="/login", method=RequestMethod.GET)
	public String login() {
		return "login";
	}
}
