package cn.com.qmth.stmms.biz.utils;

import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

import cn.com.qmth.stmms.biz.role.service.RoleAuthService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.common.enums.Auth;
import cn.com.qmth.stmms.common.enums.Role;

public class RoleAuthUtil {

    private static final char ROLE_NAME_SPLIT = ',';

    public static User buildRoleAuthByUser(User user, RoleAuthService service) {
        if (user != null) {
            user.setRoles(new LinkedHashSet<Role>());
            user.setAuthMap(new HashMap<String, Auth>());
            user.setRoleMap(new HashMap<String, Role>());
            String[] names = StringUtils.split(StringUtils.trimToEmpty(user.getRoleNames()), ROLE_NAME_SPLIT);
            List<String> displays = new LinkedList<String>();
            if (names != null) {
                for (String name : names) {
                    try {
                        Role role = service.findRoleByName(name);
                        if (role != null) {
                            user.getRoles().add(role);
                            user.getRoleMap().put(role.getName(), role);
                            displays.add(role.getDisplay());
                            Set<Auth> auths = service.findAuthByRole(role);
                            for (Auth auth : auths) {
                                user.getAuthMap().put(auth.getName(), auth);
                            }
                        }
                    } catch (Exception e) {
                        continue;
                    }
                }
            }
            user.setRoleDisplays(StringUtils.join(displays, ROLE_NAME_SPLIT));
        }
        return user;
    }
}
