/*********************************************************************************************************
 * 프로그램명 : UserGroup.java 프로그램설명 : 사용자 그룹지정 작성자 : 작성일 : 변경일 :
 **********************************************************************************************************/

package kr.co.kihyun.beans.user;

import java.sql.ResultSet;
import java.sql.SQLException;
import kr.co.kihyun.beans.entity.MoumiEntity;
import kr.co.kihyun.beans.entity.MDept;
import kr.co.kihyun.beans.entity.UserDept;
import kr.co.kihyun.beans.entity.UserPart;
import kr.co.kihyun.beans.entity.UserUser;

import kr.co.kihyun.db.DBManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserGroup extends DBManager {
	private static final Logger LOG = LoggerFactory.getLogger(UserGroup.class);

	private ResultSet rs = null;

	private String[] userUserID = null;
	private String[] userUserName = null;
	private String[] userDeptID = null;
	private boolean[] userValid = null;
	private int userCount = 0;

	public int getDeptCount(String partID) {
		StringBuilder sql = new StringBuilder(70);
		int count = 0;

		try {
			//sql.append("select count(*) from ")
			//		.append(MoumiEntity.getTableName(UserDept.class)).append(" where part_id=?");
                        
                        // 2014.09.22 BY YOUNGJUN CHO(폐교 제외조건 추가)
                        sql.append("SELECT COUNT(*)     \n");
                        sql.append("FROM " + MoumiEntity.getTableName(UserDept.class) + " UD   \n");
                        sql.append("    ," + MoumiEntity.getTableName(MDept.class) + " DT   \n");
                        sql.append("WHERE UD.ID = DT.ID     \n");
                        sql.append("    AND UD.PART_ID = ?     \n");
                        sql.append("    AND DT.IS_OUT = 'N'     \n");
//System.out.println("=====> call getDeptCount(String partID) SQL : \n" + sql.toString());
			rs = execQuery(sql, partID);
			if (rs.next()) {
				count = rs.getInt(1);
			}

			return count;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nError Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	public String getUserID(String partID) {
		StringBuilder sql = new StringBuilder(60);
		String usID = "";

		try {
			sql.append("select user_id from ").append(MoumiEntity.getTableName(UserPart.class)).append(" where id=?");
			rs = execQuery(sql, partID);

			if (rs.next()) {
				usID = rs.getString(1);
			}

			return usID;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nError Code - {}\nmessage - {}\nsql - {}", new Object[] { sqlEx.getSQLState(),
					sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	public String[] getDeptID(String partID) {
		StringBuilder sql = new StringBuilder(80);
		int count = 0;
		String[] deptID = null;
		try {
			//sql.append("select id from ")
			//		.append(MoumiEntity.getTableName(UserDept.class)).append(" where part_id=? order by name");
                    
                        // 2014.09.22 BY YOUNGJUN CHO(폐교 제외조건 추가)
                        sql.append("SELECT UD.ID     \n");
                        sql.append("FROM " + MoumiEntity.getTableName(UserDept.class) + " UD   \n");
                        sql.append("    ," + MoumiEntity.getTableName(MDept.class) + " DT   \n");
                        sql.append("WHERE UD.ID = DT.ID     \n");
                        sql.append("    AND UD.PART_ID = ?     \n");
                        sql.append("    AND DT.IS_OUT = 'N'     \n");
                        sql.append("ORDER BY UD.NAME ASC     \n");
//System.out.println("=====> call getDeptID(String partID) SQL : \n" + sql.toString());

			rs = execQuery(sql, partID);
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return null;
			}

			deptID = new String[count];

			for (int i = 0; rs.next(); i++) {
				deptID[i] = rs.getString(1);
			}
			return deptID;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nError Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	public String[] getDeptName(String partID) {
		StringBuilder sql = new StringBuilder(80);
		int count = 0;
		String[] deptName = null;
		try {
			//sql.append("SELECT name FROM ").append(MoumiEntity.getTableName(UserDept.class))
			//		.append(" WHERE part_id=? order by name");
                    
                        // 2014.09.22 BY YOUNGJUN CHO(폐교 제외조건 추가)
                        sql.append("SELECT UD.NAME     \n");
                        sql.append("FROM " + MoumiEntity.getTableName(UserDept.class) + " UD   \n");
                        sql.append("    ," + MoumiEntity.getTableName(MDept.class) + " DT   \n");
                        sql.append("WHERE UD.ID = DT.ID     \n");
                        sql.append("    AND UD.PART_ID = ?     \n");
                        sql.append("    AND DT.IS_OUT = 'N'     \n");
                        sql.append("ORDER BY UD.NAME ASC     \n");
//System.out.println("=====> call getDeptName(String partID) SQL : \n" + sql.toString());
			rs = execQuery(sql, partID);
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return null;
			}

			deptName = new String[count];

			for (int i = 0; rs.next(); i++) {
				deptName[i] = rs.getString(1);
			}
			return deptName;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nError Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}
        
        /*
         * 2014.09.19 Add by KWON,HAN : 
         */
	public String[] getOrganNameOfUpperDept(String partID) {
		StringBuilder sql = new StringBuilder(1000);
		int count = 0;
		String[] organDeptName = null;
		try {
            
			sql.append("SELECT ( SELECT name FROM ").append(MoumiEntity.getTableName(MDept.class)).append(" where id = ( CASE WHEN dt.id = dt.organ AND dt.upper_dept IS NOT NULL   \n") 
                           .append("                                                       THEN ( SELECT organ FROM ").append(MoumiEntity.getTableName(MDept.class)).append(" WHERE id = dt.upper_dept )    \n")
                           .append("                                                       ELSE dt.organ END )    \n")
                           .append("        ) AS organ_dept_name   \n")
                           .append("  FROM ").append(MoumiEntity.getTableName(UserDept.class)).append("  a   \n")
                           .append("     , ").append(MoumiEntity.getTableName(MDept.class)).append("  dt   \n")
			   .append(" WHERE a.part_id = ?   \n" )
                           .append("   AND a.id = dt.id(+)   \n" )
                           // 2014.09.22 BY YOUNGJUN CHO(폐교 제외조건 추가)
                           .append("   AND dt.IS_OUT = 'N'   \n" )     
                           .append(" ORDER BY a.name   \n");

//System.out.println("UserGroup.getOrganDeptName ===");
//System.out.println("sql = \n" + sql);
//System.out.println("==============================");          

			rs = execQuery(sql, partID);
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return null;
			}

			organDeptName = new String[count];

			for (int i = 0; rs.next(); i++) {
				organDeptName[i] = rs.getString(1);
			}
			return organDeptName;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nError Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}
        
        /*
         * 2014.09.19 Add by KWON,HAN : 
         */
	public String[] getUpperDeptName(String partID) {
		StringBuilder sql = new StringBuilder(1000);
		int count = 0;
		String[] upperDeptName = null;
		try {
			sql.append("SELECT ( SELECT name FROM ").append(MoumiEntity.getTableName(MDept.class)).append(" WHERE id = dt.upper_dept ) AS upper_dept_name   \n")
                           .append("  FROM ").append(MoumiEntity.getTableName(UserDept.class)).append("  a   \n")
                           .append("     , ").append(MoumiEntity.getTableName(MDept.class)).append("  dt   \n")
			   .append(" WHERE a.part_id = ?   \n" )
                           .append("   AND a.id = dt.id(+)   \n" )
                           // 2014.09.22 BY YOUNGJUN CHO(폐교 제외조건 추가)
                           .append("   AND dt.IS_OUT = 'N'   \n" )     
                           .append(" ORDER BY a.name   \n");

//System.out.println("UserGroup.getUpperDeptName ===");
//System.out.println("sql = \n" + sql);
//System.out.println("==============================");          

			rs = execQuery(sql, partID);
			if (rs != null) {
				rs.last();
				count = rs.getRow();
				rs.beforeFirst();
			} else {
				return null;
			}

			upperDeptName = new String[count];

			for (int i = 0; rs.next(); i++) {
				upperDeptName[i] = rs.getString(1);
			}
			return upperDeptName;
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nError Code - {}\nmessage - {}\nsql - {}",
					new Object[] { sqlEx.getSQLState(), sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}
        

	public void userSetting(String partID) {
		StringBuilder sql = new StringBuilder(160);
		userCount = 0;
		try {
			sql.append("SELECT id, name, dept_id, case when valid = 'Y' and valid <> '0' then 1 else 0 end valid FROM ")
					.append(MoumiEntity.getTableName(UserUser.class)).append(" WHERE part_id=? order by name");

			rs = execQuery(sql, partID);
			if (rs != null) {
				rs.last();
				userCount = rs.getRow();
				rs.beforeFirst();
			} else {
				return;
			}

			userDeptID = new String[userCount];
			userUserID = new String[userCount];
			userUserName = new String[userCount];
			userValid = new boolean[userCount];

			for (int i = 0; rs.next(); i++) {
				userUserID[i] = rs.getString(1);
				userUserName[i] = rs.getString(2);
				userDeptID[i] = rs.getString(3);
				userValid[i] = rs.getBoolean(4);
			}
		} catch (SQLException sqlEx) {
			LOG.error("\nSQLState - {}\nError Code - {}\nmessage - {}\nsql - {}", new Object[] { sqlEx.getSQLState(),
					sqlEx.getErrorCode(), sqlEx.getMessage(), sql });
			throw new RuntimeException(sqlEx);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		} finally {
			close(rs);
			execClose();
		}
	}

	public String[] getUserUserID() {
            //24.Public 메소드로부터 반환된 Private배열_CWE-495 : Update by KWON,HAN
	    //	return userUserID;
                
            String[] ret = null;
            if( this.userUserID != null) {
                ret = new String[userUserID.length];
                for (int i=0; i<userUserID.length; i++) {
                    ret[i] = this.userUserID[i];
                }
            }
            return ret;
            //====================================================================                 
	}

	public String[] getUserUserName() {
	    //	return userUserName;
                
            String[] ret = null;
            if( this.userUserName != null) {
                ret = new String[userUserName.length];
                for (int i=0; i<userUserName.length; i++) {
                    ret[i] = this.userUserName[i];
                }
            }
            return ret;                
	}

	public String[] getUserDeptID() {
	    //	return userDeptID;
                
            String[] ret = null;
            if( this.userDeptID != null) {
                ret = new String[userDeptID.length];
                for (int i=0; i<userDeptID.length; i++) {
                    ret[i] = this.userDeptID[i];
                }
            }
            return ret;                 
	}

	public int getUserCount() {
		return userCount;
	}

	public boolean[] getUserValid() {
	    //	return userValid;
                
            boolean[] ret = null;
            if( this.userValid != null) {
                ret = new boolean[userValid.length];
                for (int i=0; i<userValid.length; i++) {
                    ret[i] = this.userValid[i];
                }
            }
            return ret;                
	}
}
