package com.dev.swms.server.service.security.pojo;

import com.dev.swms.server.service.security.RightsExpandManager;
import com.dev.energy.server.model.security.BussinessPermission;
import com.dev.energy.server.model.security.Group;
import com.dev.energy.server.model.security.PagePermission;
import com.dev.energy.server.model.security.Permission;
import com.dev.energy.server.model.security.Role;
import com.dev.energy.server.model.security.User;
import com.dev.energy.server.model.welcomepage.WelcomePage;
import com.dev.energy.server.service.pojo.DefaultBaseManager;

/**
 * @author  dev
 *
 */
public class DefaultRightsExpandManager extends DefaultBaseManager implements RightsExpandManager {

	/**
	 * 组拷贝
	 */
	public void copyGroups(Group group) {
		Group oldGroup = commonDao.load(Group.class,group.getId());

		Group  newGroup = new Group();
		newGroup.setCode(group.getCode());
		newGroup.setName(group.getName());
		
	    for(Role oldRole : oldGroup.getRoles()){
	    	newGroup.getRoles().add(oldRole);
	    }
		
		commonDao.store(newGroup);
	}

	/**
	 * 角色拷贝
	 */
	public void copyRights(Role role) {
	    Role oldRole = commonDao.load(Role.class,role.getId());
	    
		Role  newRole = new Role();
		newRole.setCode(role.getCode());
		newRole.setName(role.getName());
		
	    for(Permission oldPermission : oldRole.getPermissions()){
	    	if (oldPermission instanceof PagePermission) {
		    	PagePermission permission = new PagePermission();
		    	addPermission(newRole, oldPermission, permission);
	    	} else {
		    	BussinessPermission permission = new BussinessPermission();
		    	addPermission(newRole, oldPermission, permission);
	    	}
	    }
		
		commonDao.store(newRole);
	
	}
	
	/**
	 * 类似创建用户
	 */
	public void similarCreateUser(User user) {
		
		User oldUser = commonDao.load(User.class,user.getId());
		
		User newUser = new User();
		
		
		newUser.setLoginName(user.getLoginName());
		newUser.setName(user.getName());
		newUser.setPassword(user.getPassword());
		newUser.setLocale(user.getLocale());
		newUser.setEmail(user.getEmail());
		newUser.setExpiryDate(user.getExpiryDate());
		newUser.setPasswordExpiryDate(user.getPasswordExpiryDate());
		newUser.setFirstPage(user.getFirstPage().getId()==null?null:commonDao.load(WelcomePage.class, user.getFirstPage().getId()));
		
		
		for(Group oldGroup : oldUser.getGroups()){
			newUser.getGroups().add(oldGroup);
		}
		
		commonDao.store(newUser);
	
	}
	

	private void addPermission(Role newRole, Permission oldPermission, Permission permission) {
    	permission.setRole(newRole);
    	permission.setProject(oldPermission.getProject());
    	permission.setElementId(oldPermission.getElementId());
    	permission.setExpression(oldPermission.getExpression());
    	permission.setReferenceModel(oldPermission.getReferenceModel());
    	newRole.getPermissions().add(permission);
	}


   
}
