/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * Copyright (C) 2004-2011 Aimluck,Inc.
 * http://www.aipo.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.aimluck.eip.webmail;

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

import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;

import com.aimluck.commons.field.ALStringField;
import com.aimluck.commons.utils.ALStringUtil;
import com.aimluck.eip.addressbookuser.beans.AddressBookUserEmailLiteBean;
import com.aimluck.eip.addressbookuser.beans.AddressBookUserGroupLiteBean;
import com.aimluck.eip.addressbookuser.util.AddressBookUserUtils;
import com.aimluck.eip.cayenne.om.account.EipMUserPosition;
import com.aimluck.eip.cayenne.om.portlet.EipMAddressGroup;
import com.aimluck.eip.cayenne.om.security.TurbineGroup;
import com.aimluck.eip.cayenne.om.security.TurbineUser;
import com.aimluck.eip.cayenne.om.security.TurbineUserGroupRole;
import com.aimluck.eip.common.ALAbstractFormData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALEipGroup;
import com.aimluck.eip.common.ALEipManager;
import com.aimluck.eip.common.ALEipPost;
import com.aimluck.eip.common.ALEipUser;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.modules.actions.common.ALAction;
import com.aimluck.eip.orm.Database;
import com.aimluck.eip.orm.query.SelectQuery;
import com.aimluck.eip.user.beans.UserGroupLiteBean;
import com.aimluck.eip.user.beans.UserGroupPositionLiteBean;
import com.aimluck.eip.user.util.UserUtils;
import com.aimluck.eip.util.ALEipUtils;

/**
 * メール送信時に使用するアドレス帳のフォームデータを管理するためのクラスです。 <br />
 */
public class WebMailAddressbookFormData extends ALAbstractFormData {

  private static final JetspeedLogger logger =
    JetspeedLogFactoryService.getLogger(WebMailAddressbookFormData.class
      .getName());

  /** 社内 */
  public static final int TYPE_EXTERNAL = 0;

  /** 社外 */
  public static final int TYPE_INTERNAL = 1;

  /** 社内／社外 */
  private ALStringField type_company = null;

  private List<ALEipGroup> internalGroupList = null;

  private List<AddressBookUserGroupLiteBean> externalGroupList = null;

  private ALStringField current_internal_group_name = null;

  private ALStringField current_external_group_name = null;

  private ArrayList<ALStringField> toRecipientList = null;

  private ArrayList<ALStringField> ccRecipientList = null;

  private ArrayList<ALStringField> bccRecipientList = null;

  /**  */
  private int userId = -1;

  // add by motegi start 部署階層化
  // ログインユーザーの所属する部署2
  private String current_group_name;

  // ログインユーザーの所属する部署1
  private String current_parent_group_name;

  // add end

  @Override
  public void init(ALAction action, RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {
    super.init(action, rundata, context);

    userId = ALEipUtils.getUserId(rundata);

    List<ALEipGroup> myGroups = ALEipUtils.getMyGroups(rundata);
    internalGroupList = new ArrayList<ALEipGroup>();
    if (myGroups != null) {
      int length = myGroups.size();
      for (int i = 0; i < length; i++) {
        internalGroupList.add(myGroups.get(i));
      }
    }

    externalGroupList =
      AddressBookUserUtils.getAddressBookUserGroupLiteBeans(rundata);
    // add start
    // 「未所属」を先頭に追加
    EipMAddressGroup defaultGroup;
    try {
      defaultGroup = AddressBookUserUtils.getDefaultEipMAddressGroup();
      AddressBookUserGroupLiteBean bean = new AddressBookUserGroupLiteBean();
      bean.initField();
      bean.setGroupId(defaultGroup.getGroupId().intValue());
      bean.setName(AddressBookUserUtils.EMPTY_COMPANY_NAME);
      externalGroupList.add(0, bean);
    } catch (Exception e) {
      throw new ALPageNotFoundException();
    }
    // add end

    toRecipientList = new ArrayList<ALStringField>();
    ccRecipientList = new ArrayList<ALStringField>();
    bccRecipientList = new ArrayList<ALStringField>();

    try {
      String[] detail_to_recipients =
        rundata.getParameters().getStrings("detail_to_recipients");
      if (detail_to_recipients != null) {
        int length = detail_to_recipients.length;
        for (int i = 0; i < length; i++) {
          toRecipientList.add(new ALStringField(new String(
            detail_to_recipients[i].getBytes("8859_1"),
            "utf-8")));
        }
      }

      String[] detail_cc_recipients =
        rundata.getParameters().getStrings("detail_cc_recipients");
      if (detail_cc_recipients != null) {
        int length = detail_cc_recipients.length;
        for (int i = 0; i < length; i++) {
          ccRecipientList.add(new ALStringField(new String(
            detail_cc_recipients[i].getBytes("8859_1"),
            "utf-8")));
        }
      }

      String[] detail_bcc_recipients =
        rundata.getParameters().getStrings("detail_bcc_recipients");
      if (detail_bcc_recipients != null) {
        int length = detail_bcc_recipients.length;
        for (int i = 0; i < length; i++) {
          bccRecipientList.add(new ALStringField(new String(
            detail_bcc_recipients[i].getBytes("8859_1"),
            "utf-8")));
        }
      }

      // add by motegi start 代理送信対応
      // 現在のユーザー名を取得する
      ALEipUser loginuser = ALEipUtils.getALEipUser(rundata);
      // ログインユーザーの所属部署1,部署2を取得する
      List<UserGroupPositionLiteBean> list =
        UserUtils.getPostPositionBeanList((int) loginuser
          .getUserId()
          .getValue());
      if (list != null && list.size() > 0) {
        UserGroupPositionLiteBean b = list.get(0);
        current_parent_group_name = b.getPost1GroupName();
        current_group_name = b.getPost2GroupName();
      }
      // add end

    } catch (Exception ex) {
      logger.error("Exception", ex);
    }
  }

  /**
   * 
   */
  @Override
  protected void setValidator() {
    // グループ名
    current_internal_group_name.setNotNull(true);
    // グループ名
    current_external_group_name.setNotNull(true);
  }

  /**
   * 
   */
  @Override
  protected boolean validate(List<String> msgList) {
    return (msgList.size() == 0);
  }

  /**
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return
   * @throws ALPageNotFoundException
   * @throws ALDBErrorException
   */
  @Override
  protected boolean setFormData(RunData rundata, Context context,
      List<String> msgList) throws ALPageNotFoundException, ALDBErrorException {

    boolean res = super.setFormData(rundata, context, msgList);
    if (res) {
      try {
        String str[] = rundata.getParameters().getStrings("detail_recipients");
        if (str == null) {
          return res;
        }

        ALStringField field = null;
        int size = str.length;
        for (int i = 0; i < size; i++) {
          field = new ALStringField();
          field.setValue(ALStringUtil.unsanitizing(new String(str[i]
            .getBytes("8859_1"), "UTF-8")));
          toRecipientList.add(field);
          ccRecipientList.add(field);
          bccRecipientList.add(field);
        }

      } catch (Exception ex) {
        logger.error("Exception", ex);
      }
    }
    return res;
  }

  /**
   * 返信と転送時にグローバル変数に値をセットする． 返信と転送時には，ENTITY_ID がセッションに既にセットされている状態になっている．
   * 
   */
  @Override
  protected boolean loadFormData(RunData rundata, Context context,
      List<String> msgList) {
    boolean res = false;
    try {
      res = setFormData(rundata, context, msgList);
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return false;
    }
    return res;
  }

  /**
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return
   */
  @Override
  protected boolean insertFormData(RunData rundata, Context context,
      List<String> msgList) {
    return false;
  }

  /**
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return
   */
  @Override
  protected boolean updateFormData(RunData rundata, Context context,
      List<String> msgList) {
    return false;
  }

  /**
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return
   */
  @Override
  protected boolean deleteFormData(RunData rundata, Context context,
      List<String> msgList) {
    return false;
  }

  /**
   * 
   */
  public void initField() {
    // 社内／社外
    type_company = new ALStringField();
    type_company.setFieldName("社内／社外");
    type_company.setValue(Integer.toString(TYPE_INTERNAL));

    // グループ名
    current_internal_group_name = new ALStringField();
    current_internal_group_name.setFieldName("グループ名");
    current_internal_group_name.setValue("all");

    // グループ名
    current_external_group_name = new ALStringField();
    current_external_group_name.setFieldName("グループ名");
    current_external_group_name.setValue("all");
  }

  /**
   * 
   * @param groupname
   * @return
   */
  public List<TurbineUser> getInternalUsers() {
    String groupName = getCurrentInternalGroupName().toString();
    if (groupName == null || groupName.equals("") || groupName.equals("all")) {
      groupName = "LoginUser";
    }
    return getPostMygroupUsers(groupName);
  }

  /**
   * 外部アドレス取得処理を開始します。
   * 
   * @return
   */
  public List<AddressBookUserEmailLiteBean> getExternalUsers() {
    String groupId = getCurrentExternalGroupName().toString();
    try {
      return AddressBookUserUtils.getAddressBookUserEmailLiteBeansFromGroup(
        groupId,
        Integer.valueOf(userId));
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  /**
   * 指定した部署や My グループに属するユーザのリストを取得する．
   * 
   * @param groupName
   * @return
   */
  private List<TurbineUser> getPostMygroupUsers(String groupName) {
    try {
      SelectQuery<TurbineUser> query = Database.query(TurbineUser.class);

      Expression exp1 =
        ExpressionFactory.matchExp(TurbineUser.TURBINE_USER_GROUP_ROLE_PROPERTY
          + "."
          + TurbineUserGroupRole.TURBINE_GROUP_PROPERTY
          + "."
          + TurbineGroup.GROUP_NAME_PROPERTY, groupName);
      Expression exp2 =
        ExpressionFactory.matchExp(TurbineUser.DISABLED_PROPERTY, "F");
      query.setQualifier(exp1.andExp(exp2));
      query.orderAscending(TurbineUser.EIP_MUSER_POSITION_PROPERTY
        + "."
        + EipMUserPosition.POSITION_PROPERTY);

      return query.fetchList();
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }

  /**
   * 
   * @return
   */
  // public Map<Integer, ALEipPost> getPostMap() {
  // return ALEipManager.getInstance().getPostMap();
  // }
  /**
   * 部署1一覧取得処理
   * 
   * 部署1一覧を取得します。
   * 
   * @return 部署1一覧
   * @author motegi （部署階層化対応）
   */
  public static List<ALEipPost> getPostMap() {
    List<ALEipPost> rtn = ALEipManager.getInstance().getPost1Map();
    ALEipPost gs = new ALEipPost();
    gs.initField();
    gs.setGroupName(ALEipUtils.GROUPSEND_WITHOUT_POST);
    gs.setPostName("役職・役割から選ぶ");
    rtn.add(0, gs);

    ALEipPost gs_without_post = new ALEipPost();
    gs_without_post.initField();
    gs_without_post.setGroupName(ALEipUtils.GROUPSEND);
    gs_without_post.setPostName("グループ送信");
    rtn.add(gs_without_post);
    return rtn;
  }

  /**
   * 宛先のリストを取得する．
   * 
   * @return
   */
  public List<ALStringField> getToRecipientList() {
    return toRecipientList;
  }

  public List<ALStringField> getCcRecipientList() {
    return ccRecipientList;
  }

  public List<ALStringField> getBccRecipientList() {
    return bccRecipientList;
  }

  public ALStringField getTypeCompany() {
    return type_company;
  }

  public void setTypeCompany(String string) {
    type_company.setValue(string);
  }

  /**
   * 
   * @return
   */
  public List<ALEipGroup> getInternalGroupList() {
    return internalGroupList;
  }

  public List<AddressBookUserGroupLiteBean> getExternalGroupList() {
    return externalGroupList;
  }

  public ALStringField getCurrentInternalGroupName() {
    return current_internal_group_name;
  }

  public void setCurrentInternalGroupName(String string) {
    current_internal_group_name.setValue(string);
  }

  public ALStringField getCurrentExternalGroupName() {
    return current_external_group_name;
  }

  public void setCurrentExternalGroupName(String string) {
    current_external_group_name.setValue(string);
  }

  // add by motegi 部署階層化対応

  public String getCurrentGroupName() {
    return current_group_name;
  }

  public String getCurrentParentGroupName() {
    return current_parent_group_name;
  }

  public List<UserGroupLiteBean> getChildGroupList() {

    if (current_parent_group_name != null
      && current_parent_group_name.length() > 0) {
      return UserUtils.getPost2LiteBeans(current_parent_group_name);
    }
    return new ArrayList<UserGroupLiteBean>();
  }

  // add end
}
