/**
 * Copyright(C) 2014-2015 CHCP 
 * Licensed to CHCP under Apache License Version 2.0
 * Author: Gordon Wang
 */

package org.chcp.framework.user.user;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.chcp.framework.user.domain.dao.UserDao;
import org.chcp.framework.user.domain.entity.Role;
import org.chcp.framework.user.domain.entity.User;
import org.chcp.framework.user.domain.service.UserService;

//Service定义Transaction，DAO层是否还要定义
@Service
@Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT, readOnly=false, rollbackFor=Exception.class)
public class UserServiceImpl implements UserService
{
	private static Logger logger =LoggerFactory.getLogger(UserServiceImpl.class);

	@Autowired
	private UserDao userDao;
	
	public User createUser(User user) throws Exception
	{
		/*
		User admin = new User();
		admin.setUserName("admin");
		admin.setPassword("admin");
		admin.setIntro("Administrator user.");
		
		List<String> list = new ArrayList<String>();
		list.add(Role.ROLE_ADMIN);
		admin.setAddRoles(list);
		userService.createUser(admin);
		*/
		
		//查询userId是否存在，存在的话抛出异常。
		if(null != userDao.findById(user.getUserId())) 
		{
			throw new Exception("UserId " + user.getUserId() + "already exist, can't create the same Id user.");
		}
		
		userDao.save(user);
		
		return user;
	}
	
	public User updateUser(User user) throws Exception
	{ 
		User result = userDao.findByUserName(user.getUserName());
		if(null == result)
		{
			throw new Exception("Can't find user:" + user.getUserName());
		}
		
		//对每一项进行比较，如果变化则赋值
		if(!result.getFirstName().equals(user.getFirstName()))
		{ 
			result.setFirstName(user.getFirstName());
		}
		userDao.update(result);

		return result;
	}

	public int deleteUser(List<String> userNames) throws Exception
	{
		return userDao.deleteByUserName(userNames);
	}

	public User getUserByName(String userName) throws Exception
	{
		User result = userDao.findByUserName(userName);
		
		if(null == result)
		{
			throw new Exception("Can't find user, name is:" + userName);
		}
		
		return result;
	}

	@SuppressWarnings("unchecked")
	public List<User> getUserList(int start, int limit, String sortBy, String direction, StringBuffer totalSize) throws Exception
	{
		//totalSize作为出参返回符合条件记录条数
		totalSize.append(userDao.getCount());
		return (List<User>) userDao.findList(start, limit, sortBy, direction);
	}
}