/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * Copyright (C) 2004-2008 Aimluck,Inc.
 * http://aipostyle.com/
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.aimluck.eip.account.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.SelectQuery;
import org.apache.jetspeed.services.JetspeedSecurity;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.jetspeed.services.resources.JetspeedResources;
import org.apache.jetspeed.services.security.UnknownUserException;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;

import com.aimluck.eip.cayenne.om.account.EipMCompany;
import com.aimluck.eip.cayenne.om.account.EipMPosition;
import com.aimluck.eip.cayenne.om.account.EipMPost;
import com.aimluck.eip.cayenne.om.security.TurbineGroup;
import com.aimluck.eip.cayenne.om.security.TurbineUserGroupRole;
import com.aimluck.eip.common.ALBaseUser;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.user.beans.UserGroupLiteBean;
import com.aimluck.eip.util.ALEipUtils;

/**
 * ユーザーアカウントのユーティリティクラスです
 */
public class AccountUtils {

  /** logger */
  private static final JetspeedLogger logger = JetspeedLogFactoryService
      .getLogger(AccountUtils.class.getName());

  /** CSVファイルを一時保管するディレクトリの指定 */
  public static final String FOLDER_TMP_FOR_CSV_FILES = JetspeedResources
      .getString("aipo.tmp.directory", "");

  /** CSVファイル名 */
  public static final String FOLDER_TMP_FOR_USERINFO_CSV_FILENAME = "user_info.csv";

  public static final int CSV_FILE_COL_COUNT = 11;

  /**
   * セッション中のエンティティIDで示されるユーザ情報を取得する。 論理削除されたユーザを取得した場合はnullを返す。
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static ALBaseUser getBaseUser(RunData rundata, Context context) {
    String userid = ALEipUtils.getTemp(rundata, context,
        ALEipConstants.ENTITY_ID);
    try {
      if (userid == null) {
        logger.debug("Empty ID...");
        return null;
      }
      ALBaseUser user = (ALBaseUser) JetspeedSecurity.getUser(userid);
      // 削除済みユーザの取得は行わない。
      // By Haruo Kaneko
      if ("T".equals(user.getDisabled())) {
        return null;
      } else {
        return (ALBaseUser) JetspeedSecurity.getUser(userid);
      }
    } catch (UnknownUserException uex) {
      logger.error("UnknownUserException : UserID = " + userid);
      return null;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  /**
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static EipMCompany getEipMCompany(RunData rundata, Context context) {
    EipMCompany result = null;
    String id = ALEipUtils.getTemp(rundata, context, ALEipConstants.ENTITY_ID);
    try {
      if (id == null || Integer.valueOf(id) == null) {
        logger.debug("Empty ID...");
        return result;
      }

      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
      Expression exp = ExpressionFactory.matchDbExp(
          EipMCompany.COMPANY_ID_PK_COLUMN, Integer.valueOf(id));
      SelectQuery query = new SelectQuery(EipMCompany.class, exp);
      List list = dataContext.performQuery(query);
      if (list == null || list.size() == 0) {
        logger.debug("Not found ID...");
        return result;
      }
      result = (EipMCompany) list.get(0);
    } catch (Exception ex) {
      logger.error("Exception", ex);
    }
    return result;
  }

  /**
   * セッションに格納されているIDを用いて、部署情報を取得します。
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static EipMPost getEipMPost(RunData rundata, Context context) {
    EipMPost result = null;
    String id = ALEipUtils.getTemp(rundata, context, ALEipConstants.ENTITY_ID);
    try {
      if (id == null || Integer.valueOf(id) == null) {
        logger.debug("Empty ID...");
        return result;
      }

      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
      Expression exp = ExpressionFactory.matchDbExp(EipMPost.POST_ID_PK_COLUMN,
          Integer.valueOf(id));
      SelectQuery query = new SelectQuery(EipMPost.class, exp);
      List list = dataContext.performQuery(query);
      if (list == null || list.size() == 0) {
        logger.debug("Not found ID...");
        return result;
      }
      result = (EipMPost) list.get(0);
    } catch (Exception ex) {
      logger.error("Exception", ex);
    }
    return result;
  }

  /**
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static EipMPosition getEipMPosition(RunData rundata, Context context) {
    EipMPosition result = null;
    String id = ALEipUtils.getTemp(rundata, context, ALEipConstants.ENTITY_ID);
    try {
      if (id == null || Integer.valueOf(id) == null) {
        logger.debug("Empty ID...");
        return result;
      }

      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
      Expression exp = ExpressionFactory.matchDbExp(
          EipMPosition.POSITION_ID_PK_COLUMN, Integer.valueOf(id));
      SelectQuery query = new SelectQuery(EipMPosition.class, exp);
      List list = dataContext.performQuery(query);
      if (list == null || list.size() == 0) {
        logger.debug("Not found ID...");
        return result;
      }
      result = (EipMPosition) list.get(0);
    } catch (Exception ex) {
      logger.error("Exception", ex);
    }
    return result;
  }

  public static String[] getCsvSplitStrings(String line) {
    if (line == null || line.equals(""))
      return null;

    try {
      ArrayList list = new ArrayList();
      int count_comma = 0;
      char c;
      StringBuffer token = new StringBuffer("");
      int len = line.length();
      for (int i = 0; i < len; i++) {
        c = line.charAt(i);
        if (c != ',' && i == len - 1) {
          token.append(c);
          list.add(token.toString());
        } else if (c == ',') {
          list.add(token.toString());
          token = new StringBuffer("");
          count_comma++;
          continue;
        } else {
          token.append(c);
        }
        if (count_comma > AccountUtils.CSV_FILE_COL_COUNT) {
          break;
        }
      }

      if (line.endsWith(",")) {
        list.add("");
      }

      String[] strings = new String[list.size()];
      strings = (String[]) list.toArray(strings);
      return strings;
    } catch (Exception e) {
      return null;
    }
  }

  /**
   * ユーザーの所属する部署の一覧を取得します。
   * 
   * @param uid
   *            ユーザーID
   * @return 所属する部署リスト
   */
  public static List getPostBeanList(int uid) {
    SelectQuery query = new SelectQuery(TurbineUserGroupRole.class);
    Expression exp1 = ExpressionFactory.matchExp(
        TurbineUserGroupRole.TURBINE_USER_PROPERTY, Integer.valueOf(uid));
    Expression exp2 = ExpressionFactory.greaterExp(
        TurbineUserGroupRole.TURBINE_GROUP_PROPERTY, Integer.valueOf(3));
    Expression exp3 = ExpressionFactory.matchExp(
        TurbineUserGroupRole.TURBINE_GROUP_PROPERTY + "."
            + TurbineGroup.OWNER_ID_PROPERTY, Integer.valueOf(1));
    query.setQualifier(exp1);
    query.andQualifier(exp2);
    query.andQualifier(exp3);
    DataContext dataContext = DatabaseOrmService.getInstance().getDataContext();
    List list = dataContext.performQuery(query);

    if (list == null || list.size() < 0) {
      return null;
    }

    List resultList = new ArrayList();

    TurbineUserGroupRole ugr = null;
    TurbineGroup group = null;
    UserGroupLiteBean bean = null;
    int size = list.size();
    for (int i = 0; i < size; i++) {
      ugr = (TurbineUserGroupRole) list.get(i);
      group = ugr.getTurbineGroup();
      bean = new UserGroupLiteBean();
      bean.initField();
      bean.setGroupId(group.getName());
      bean.setName(group.getGroupAliasName());
      resultList.add(bean);
    }

    return resultList;
  }
}
