/*
 * Copyright 2002-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
package com.sds.emp.user.services.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import anyframe.core.properties.IPropertiesService;
import anyframe.core.query.IQueryService;

import com.sds.emp.common.Page;
import com.sds.emp.user.services.SearchVO;
import com.sds.emp.user.services.UserVO;

public class UserDAO {

	/** an instance variable for the queryService. */
	protected IQueryService queryService;

	/** an instance variable for the propertiesService. */
	protected IPropertiesService propertiesService;

	/**
	 * Sets the name of the QueryService to use.
	 * 
	 * @param queryService
	 *            queryService for this member
	 */
	public void setQueryService(IQueryService queryService) {
		this.queryService = queryService;
	}

	/**
	 * Sets the name of the PropertiesService to use.
	 * 
	 * @param propertiesService
	 *            propertiesService for this member.
	 */
	public void setPropertiesService(IPropertiesService propertiesService) {
		this.propertiesService = propertiesService;
	}

	/**
	 * Returns User List based on <code>searchVO.getSearchCondition()</code>
	 * if value is 0 then userId is used else userName is used. Wild card parten %
	 * is added to the search
	 * 
	 * @param searchVO
	 *            search criteria.
	 * @return Page as User List.
	 * @throws Exception
	 *             if query fails.
	 */
	public Page getUserList(SearchVO searchVO) throws Exception {
		int pageIndex = searchVO.getPageIndex();
		int pageSize = propertiesService.getInt("PAGE_SIZE");
		int pageUnit = propertiesService.getInt("PAGE_UNIT");

		Object[] iVal = new Object[1];

		String searchCondition = searchVO.getSearchCondition();
		String searchKeyword = searchVO.getSearchKeyword();

		if ("".equals(searchCondition) || "0".equals(searchCondition))
			iVal[0] = "userId=%" + searchKeyword + "%";
		else
			iVal[0] = "userName=%" + searchKeyword + "%";

		Map userListMap = queryService.findWithRowCount("getUserList",
				iVal, pageIndex, pageSize);

		ArrayList resultList = (ArrayList) userListMap.get(IQueryService.LIST);
		int totalSize = ((Long) userListMap.get(IQueryService.COUNT))
				.intValue();
		Page resultPage = new Page(resultList, (new Integer(pageIndex))
				.intValue(), totalSize, pageUnit, pageSize);

		return resultPage;

	}

	/**
	 * Returns UserVO for the given user id.
	 * 
	 * @param userId
	 *            search criteria.
	 * @return <code>UserVO</code> if found else <code>null</code>
	 * @throws Exception
	 *             if query fails.
	 */
	public UserVO getUser(String userId) throws Exception {

		Collection userCollection = queryService.find("getUser",
				new Object[] { userId });
		Iterator userItr = userCollection.iterator();
		if (userItr.hasNext()) {
			return (UserVO) userItr.next();
		}
		return null;
	}

	/**
	 * Adds user.
	 * 
	 * @param userVO
	 *            user object
	 * @throws Exception
	 *             if query fails.
	 */
	public void addUser(UserVO userVO) throws Exception {
		String userId = userVO.getUserId();
		String userName = userVO.getUserName();
		String password = userVO.getPassword();
		String ssn = userVO.getSsn();
		String slYn = userVO.getSlYn();
		String birthDay = userVO.getBirthDay();
		BigDecimal age = userVO.getAge();
		String cellPhone = userVO.getCellPhone();
		String addr = userVO.getAddr();
		String email = userVO.getEmail();
		String emailYn = userVO.getEmailYn();
		String imageFile = userVO.getImageFile();
		queryService.create("addUser", new Object[] { userId, userName,
				password, ssn, slYn, birthDay, age, cellPhone, addr, email,
				emailYn, imageFile });
	}

	/**
	 * Updates the given user.
	 * 
	 * @param userVO
	 *            user object
	 * @throws Exception
	 *             if query fails.
	 */
	public int updateUser(UserVO userVO) throws Exception {
		String userId = userVO.getUserId();
		String userName = userVO.getUserName();
		String ssn = userVO.getSsn();
		String slYn = userVO.getSlYn();
		String birthDay = userVO.getBirthDay();
		BigDecimal age = userVO.getAge();
		String cellPhone = userVO.getCellPhone();
		String addr = userVO.getAddr();
		String email = userVO.getEmail();
		String emailYn = userVO.getEmailYn();

		return queryService.update("updateUser", new Object[] { userName, ssn, slYn,
				birthDay, age, cellPhone, addr, email, emailYn, userId });

	}

	/**
	 * checks for duplicate value.
	 * 
	 * @param userId
	 *            search criteria.
	 * @return <code>0</code> if user does not exist else returns the number
	 *         of time user is present in system.
	 * @throws Exception
	 *             if find query fails.
	 */
	public int checkDuplication(String userId) throws Exception {
		Collection countCollection = null;

		countCollection = queryService.find("checkDuplication",
				new Object[] { userId });

		Iterator countItr = countCollection.iterator();
		if (countItr.hasNext()) {
			Map countMap = (Map) countItr.next();
			int count = ((BigDecimal) countMap.get("rowcount")).intValue();
			return count;
		}
		return 0;
	}

}

