@SuppressWarnings("unchecked")
  @Override
  public List<Country> getCountries(Language language) throws ServiceException {

    List<Country> countries = null;
    try {

      // CacheUtils cacheUtils = CacheUtils.getInstance();

      countries = (List<Country>) cache.getFromCache("COUNTRIES_" + language.getCode());

      if (countries == null) {

        countries = countryDao.listByLanguage(language);

        // set names
        for (Country country : countries) {

          CountryDescription description = country.getDescriptions().get(0);
          country.setName(description.getName());
        }

        cache.putInCache(countries, "COUNTRIES_" + language.getCode());
      }

    } catch (Exception e) {
      LOGGER.error("getCountries()", e);
    }

    return countries;
  }
  @PreAuthorize("hasRole('AUTH')")
  @RequestMapping(value = "/admin/users/save.html", method = RequestMethod.POST)
  public String saveUser(
      @Valid @ModelAttribute("user") User user,
      BindingResult result,
      Model model,
      HttpServletRequest request,
      Locale locale)
      throws Exception {

    setMenu(model, request);

    MerchantStore store = (MerchantStore) request.getAttribute(Constants.ADMIN_STORE);

    this.populateUserObjects(user, store, model, locale);

    Language language = user.getDefaultLanguage();

    Language l = languageService.getById(language.getId());

    user.setDefaultLanguage(l);

    Locale userLocale = LocaleUtils.getLocale(l);

    User dbUser = null;

    // edit mode, need to get original user important information
    if (user.getId() != null) {
      dbUser = userService.getByUserName(user.getAdminName());
      if (dbUser == null) {
        return "redirect://admin/users/displayUser.html";
      }
    }

    List<Group> submitedGroups = user.getGroups();
    Set<Integer> ids = new HashSet<Integer>();
    for (Group group : submitedGroups) {
      ids.add(Integer.parseInt(group.getGroupName()));
    }

    // validate security questions not empty
    if (StringUtils.isBlank(user.getAnswer1())) {
      ObjectError error =
          new ObjectError(
              "answer1", messages.getMessage("security.answer.question1.message", locale));
      result.addError(error);
    }

    if (StringUtils.isBlank(user.getAnswer2())) {
      ObjectError error =
          new ObjectError(
              "answer2", messages.getMessage("security.answer.question2.message", locale));
      result.addError(error);
    }

    if (StringUtils.isBlank(user.getAnswer3())) {
      ObjectError error =
          new ObjectError(
              "answer3", messages.getMessage("security.answer.question3.message", locale));
      result.addError(error);
    }

    if (user.getQuestion1().equals(user.getQuestion2())
        || user.getQuestion1().equals(user.getQuestion3())
        || user.getQuestion2().equals(user.getQuestion1())
        || user.getQuestion1().equals(user.getQuestion3())
        || user.getQuestion3().equals(user.getQuestion1())
        || user.getQuestion1().equals(user.getQuestion2())) {

      ObjectError error =
          new ObjectError(
              "question1", messages.getMessage("security.questions.differentmessages", locale));
      result.addError(error);
    }

    Group superAdmin = null;

    if (user.getId() != null && user.getId() > 0) {
      if (user.getId().longValue() != dbUser.getId().longValue()) {
        return "redirect://admin/users/displayUser.html";
      }

      List<Group> groups = dbUser.getGroups();
      // boolean removeSuperAdmin = true;
      for (Group group : groups) {
        // can't revoke super admin
        if (group.getGroupName().equals("SUPERADMIN")) {
          superAdmin = group;
        }
      }

    } else {

      if (user.getAdminPassword().length() < 6) {
        ObjectError error =
            new ObjectError(
                "adminPassword", messages.getMessage("message.password.length", locale));
        result.addError(error);
      }
    }

    if (superAdmin != null) {
      ids.add(superAdmin.getId());
    }

    List<Group> newGroups = groupService.listGroupByIds(ids);

    // set actual user groups
    user.setGroups(newGroups);

    if (result.hasErrors()) {
      return ControllerConstants.Tiles.User.profile;
    }

    String decodedPassword = user.getAdminPassword();
    if (user.getId() != null && user.getId() > 0) {
      user.setAdminPassword(dbUser.getAdminPassword());
    } else {
      String encoded = passwordEncoder.encodePassword(user.getAdminPassword(), null);
      user.setAdminPassword(encoded);
    }

    if (user.getId() == null || user.getId().longValue() == 0) {

      // save or update user
      userService.saveOrUpdate(user);

      try {

        // creation of a user, send an email
        String userName = user.getFirstName();
        if (StringUtils.isBlank(userName)) {
          userName = user.getAdminName();
        }
        String[] userNameArg = {userName};

        Map<String, String> templateTokens =
            EmailUtils.createEmailObjectsMap(request.getContextPath(), store, messages, userLocale);
        templateTokens.put(
            EmailConstants.EMAIL_NEW_USER_TEXT,
            messages.getMessage("email.greeting", userNameArg, userLocale));
        templateTokens.put(EmailConstants.EMAIL_USER_FIRSTNAME, user.getFirstName());
        templateTokens.put(EmailConstants.EMAIL_USER_LASTNAME, user.getLastName());
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_USERNAME_LABEL,
            messages.getMessage("label.generic.username", userLocale));
        templateTokens.put(EmailConstants.EMAIL_ADMIN_NAME, user.getAdminName());
        templateTokens.put(
            EmailConstants.EMAIL_TEXT_NEW_USER_CREATED,
            messages.getMessage("email.newuser.text", userLocale));
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_PASSWORD_LABEL,
            messages.getMessage("label.generic.password", userLocale));
        templateTokens.put(EmailConstants.EMAIL_ADMIN_PASSWORD, decodedPassword);
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_URL_LABEL,
            messages.getMessage("label.adminurl", userLocale));
        templateTokens.put(
            EmailConstants.EMAIL_ADMIN_URL, FilePathUtils.buildAdminUri(store, request));

        Email email = new Email();
        email.setFrom(store.getStorename());
        email.setFromEmail(store.getStoreEmailAddress());
        email.setSubject(messages.getMessage("email.newuser.title", userLocale));
        email.setTo(user.getAdminEmail());
        email.setTemplateName(NEW_USER_TMPL);
        email.setTemplateTokens(templateTokens);

        emailService.sendHtmlEmail(store, email);

      } catch (Exception e) {
        LOGGER.error("Cannot send email to user", e);
      }

    } else {
      // save or update user
      userService.saveOrUpdate(user);
    }

    model.addAttribute("success", "success");
    return ControllerConstants.Tiles.User.profile;
  }