/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.csu.sdmx.web.controllers;

import cz.csu.sdmx.constants.JSP;
import cz.csu.sdmx.constants.URL;
import cz.csu.sdmx.dao.UsersDao;
import cz.csu.sdmx.web.security.Access;
import cz.csu.sdmx.web.security.Permission;
import cz.csu.sdmx.web.security.User;
import cz.csu.sdmx.web.validators.UserValidator;
import java.util.Iterator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
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.RequestParam;

/**
 *
 * @author themi
 */
@Controller
public class UserController extends BaseController{
    public static final String USER = "user";
    public static final String PERMISSIONS = "permissions";
    
    @Autowired
    private UsersDao usersDao;
    
    @Autowired
    private UserValidator userValidator;
    
    @RequestMapping(value = URL.ADD_USER)
    @Access(Permission.ADMINISTER_USERS)
    public String addUser(Model model) {
        model.addAttribute(USER, new User());
        model.addAttribute(PERMISSIONS, Permission.values());
        return JSP.USER_ADD;
    } 
    
    @RequestMapping(value = URL.ADD_USER_SUBMIT)
    @Access(Permission.ADMINISTER_USERS)
    public String addUserSubmit(@ModelAttribute("user") User user, BindingResult result, Model model) {
        userValidator.validate(user, result);
        
        User existing = usersDao.find(user.getPersonalNumber());
        if(existing != null){
            result.addError(new ObjectError("", "There already exists user with personal number["+user.getPersonalNumber()+"]."));
        }
        
        if(result.hasErrors()){
            model.addAttribute(PERMISSIONS, Permission.values());
            return JSP.USER_ADD;
        }
        usersDao.insert(user);
        
        return URL.redirectTo(URL.USER + user.getPersonalNumber());
    } 
    
    @RequestMapping(value = URL.USERS_SEARCH)
    @Access(Permission.ADMINISTER_USERS)
    public String searchUsers(Model model, @RequestParam(value = "q", required = false) String searchValue) {
        List<User> users;
        
        if(searchValue == null)
            users = usersDao.list();
        else
            users = usersDao.getByPersonalNumberLike(searchValue);   
        
        
        User currentUser = getCurrentUser();
        
        Iterator<User> userIterator = users.iterator();
        //remove current user from list
        while(userIterator.hasNext()){
            User user = userIterator.next();
            if(user.getPersonalNumber().equals(currentUser.getPersonalNumber()))
                userIterator.remove();
        }
        
        //limit maximum of users 
        if(searchValue == null && users.size() > 5){
            users = users.subList(0, 5);
        }
        
        model.addAttribute("q", searchValue);
        model.addAttribute("users", users);
        return JSP.USERS_SEARCH;
    } 
    
    @RequestMapping(value = URL.USER_DELETE)
    @Access(Permission.ADMINISTER_USERS)
        public String deleteUser(Model model, 
            @RequestParam(value = "personalNumber") String personalNumber) {
        
        usersDao.delete(personalNumber);
        
        return URL.redirectTo(URL.USERS_SEARCH);
    }  
    
    @RequestMapping(value = URL.USER + "{personalNumber}")
    @Access(Permission.ADMINISTER_USERS)
    public String updateUser(Model model, 
            @PathVariable(value = "personalNumber") String personalNumber) {
        
        model.addAttribute(PERMISSIONS, Permission.values());
        model.addAttribute("user", usersDao.find(personalNumber));
        return JSP.USER_UPDATE;
    } 
    
    @RequestMapping(value = URL.USER_UPDATE_SUBMIT)
    @Access(Permission.ADMINISTER_USERS)
    public String updateUserSubmit(Model model, 
            @ModelAttribute("user") User user,
            BindingResult result) {
        
        model.addAttribute(PERMISSIONS, Permission.values());
        model.addAttribute("user", user);
        
        userValidator.validate(user, result);
        if(result.hasErrors())
            return JSP.USER_UPDATE;
        
       boolean updateResult = usersDao.update(user);
        if(updateResult)
            model.addAttribute("updateResult", "User was succesfully updated.");
        else
            model.addAttribute("updateResult", "User was not updated. Contact admin.");
        
        return JSP.USER_UPDATE;
    } 
}
