package cn.myapps.webservice.util;

import cn.myapps.common.model.application.Application;
import cn.myapps.common.model.role.Role;
import cn.myapps.designtime.application.service.ApplicationDesignTimeService;
import cn.myapps.designtime.common.service.DesignTimeServiceManager;
import cn.myapps.util.ObjectUtil;
import cn.myapps.webservice.WebServiceUtil;
import cn.myapps.webservice.fault.RoleServiceFault;
import cn.myapps.webservice.model.SimpleRole;

/**
 * RoleService工具类
 * @author ivan
 *
 */
public class RoleUtil {
	/**
	 * 把RoleVO转换为简单角色对象
	 * @param role 简单角色对象
	 * @param vo RoleVO
	 * @return 简单角色对象
	 * @throws Exception
	 */
	public static SimpleRole convertToSimple(SimpleRole role, Role vo)throws Exception{
		try {
			ObjectUtil.copyProperties(role, vo);
			ApplicationDesignTimeService appService = DesignTimeServiceManager.applicationDesignTimeService();
			Application app = (Application) appService.findById(vo.getApplicationid());
			if (app == null)
				throw new Exception("该应用(id=" + vo.getApplicationid() + ")不存在.");
			role.setApplicationName(app.getName());
			
			return role;
		} catch (Exception e) {
			throw new RoleServiceFault(e.getMessage());
		}
	}
	
	/**
	 * 把简单角色对象转换为RoleVO对象
	 * @param vo RoleVO
	 * @param role 简单角色对象
	 * @return RoleVO
	 * @throws Exception
	 */
	public static Role convertToVO(Role vo, SimpleRole role)throws Exception{
		try {
			vo.setId(role.getId() != null ? role.getId() : vo.getId());
			vo.setName(role.getName() != null ? role.getName() : vo.getName());
			Application application = WebServiceUtil.validateApplication(role
					.getApplicationName());
			vo.setApplicationid(application.getId());
			
			return vo;
		} catch (Exception e) {
			throw new RoleServiceFault(e.getMessage());
		}
	}
}
