package cn.com.qmth.stmms.biz.role.service.impl;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.qmth.stmms.biz.role.dao.RoleAuthDao;
import cn.com.qmth.stmms.biz.role.model.RoleAuth;
import cn.com.qmth.stmms.biz.role.service.RoleAuthService;
import cn.com.qmth.stmms.common.enums.Auth;
import cn.com.qmth.stmms.common.enums.Role;

@Service("roleAuthService")
public class RoleAuthServiceImpl implements RoleAuthService {

    private static final char AUTH_NAME_SPLIT = ',';

    @Autowired
    private RoleAuthDao roleAuthDao;

    public Set<Auth> findAuthByRole(Role role) {
        Set<Auth> set = new HashSet<Auth>();
        if (role != null) {
            RoleAuth ra = roleAuthDao.findOne(role.getName());
            if (ra != null) {
                String[] authNames = StringUtils.split(StringUtils.trimToEmpty(ra.getAuthNames()), AUTH_NAME_SPLIT);
                if (authNames != null) {
                    for (String name : authNames) {
                        Auth auth = Auth.findByName(name);
                        if (auth != null) {
                            set.add(auth);
                        }
                    }
                }
            }
        }
        return set;
    }

    @Transactional
    @CacheEvict(value = "role_cache", key = "#roleName", condition = "#roleName!=null")
    public void updateRoleAuth(String roleName, String[] authNames) {
        if (roleName != null && authNames != null) {
            RoleAuth ra = new RoleAuth();
            ra.setRoleName(roleName);
            ra.setAuthNames(StringUtils.join(authNames, AUTH_NAME_SPLIT));
            roleAuthDao.save(ra);
        }
    }

    @Cacheable(value = "role_cache", key = "#name", condition = "#name!=null")
    public Role findRoleByName(String name) {
        Role role = Role.findByName(name);
        if (role != null) {
            role.setAuths(findAuthByRole(role));
        }
        return role;
    }

    @Cacheable(value = "auth_cache", key = "#name", condition = "#name!=null")
    public Auth findAuthByName(String name) {
        return Auth.findByName(name);
    }

}
