/**
*                                                (客先名) 殿
*                                             サブシステム名
*                           機能名(ユーザーマスタ)
*
*                                                       作成:アイエムシンクタンク株式会社
*                                                       初版:年月日 by IMTT 
*                                                       改版:2010年7月19日 by トウ
*/
/*
 * 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.common;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.cayenne.DataRow;
import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.SQLTemplate;
import org.apache.cayenne.query.SelectQuery;
/* Add　2011/2/10 Otomaru Start--- */
import org.apache.cayenne.query.InsertQuery;
/* Add　2011/2/10 Otomaru End----- */
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;
/* Add　2010/7/21 tou Start--- */
import com.aimluck.commons.field.ALDateTimeField;
/* Add　2010/7/21 tou End--- */
import com.aimluck.eip.cayenne.om.portlet.ImwMHanyo;
import com.aimluck.eip.cayenne.om.portlet.ImwTOfficeCalendarMap;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.util.ALEipUtils;

/**
 * ユーザー情報を表すクラスです。 <br />
 * 
 */
public class ALBaseUser extends
    org.apache.jetspeed.om.security.BaseJetspeedUser {

  public static final String IN_TELEPHONE = "IN_TELEPHONE";

  public static final String OUT_TELEPHONE = "OUT_TELEPHONE";

  public static final String CELLULAR_PHONE = "CELLULAR_PHONE";

  public static final String CELLULAR_MAIL = "CELLULAR_MAIL";

  public static final String CELLULAR_UID = "CELLULAR_UID";

  public static final String COMPANY_ID = "COMPANY_ID";

  public static final String POST_ID = "POST_ID";

  public static final String POSITION_ID = "POSITION_ID";

  /* Add　2011/2/8 Otomaru Start--- */
  public static final String OFFICE_ID = "OFFICE_ID";
  /* Add　2011/2/8 Otomaru End----- */
  
  public static final String FIRST_NAME_KANA = "FIRST_NAME_KANA";

  public static final String LAST_NAME_KANA = "LAST_NAME_KANA";

  public static final String PHOTO = "PHOTO";

  public static final String CREATED_USER_ID = "CREATED_USER_ID";

  public static final String UPDATED_USER_ID = "UPDATED_USER_ID";

  public static final String CREATED = "CREATED";

  public static final String MODIFIED = "MODIFIED";
  
  /* Add　2010/8/24 muramoto Start--- */
  public static final String CAR_COMMUTING_FLAG = "CAR_COMMUTING_FLAG";
  /* Add　2010/8/24 muramoto End--- */
  
  /* Add　2010/7/20 tou Start--- */
  public static final String RETIRE_FLAG = "RETIRE_FLAG";

  public static final String PASSWORD_END_DATE = "PASSWORD_END_DATE";

  public static final String ENTER_COMPANY_DATE = "ENTER_COMPANY_DATE";

  public static final String BIRTHDAY = "BIRTHDAY";
  /* Add　2010/7/20 tou End--- */

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

  /**
   * 
   * 
   */
  public ALBaseUser() {
  }

  /**
   * 
   * @return
   */
  public String getInTelephone() {
    return (String) getPerm(IN_TELEPHONE);
  }

  /**
   * 
   * @param str
   */
  public void setInTelephone(String str) {
    setPerm(IN_TELEPHONE, str);
  }

  /**
   * 
   * @return
   */
  public String getOutTelephone() {
    return (String) getPerm(OUT_TELEPHONE);
  }

  /**
   * 
   * @param str
   */
  public void setOutTelephone(String str) {
    setPerm(OUT_TELEPHONE, str);
  }

  /**
   * 
   * @return
   */
  public String getCellularPhone() {
    return (String) getPerm(CELLULAR_PHONE);
  }

  /**
   * 
   * @param str
   */
  public void setCellularPhone(String str) {
    setPerm(CELLULAR_PHONE, str);
  }

  /**
   * 
   * @return
   */
  public String getCellularMail() {
    return (String) getPerm(CELLULAR_MAIL);
  }

  /**
   * 
   * @param str
   */
  public void setCellularMail(String str) {
    setPerm(CELLULAR_MAIL, str);
  }

  /**
   * 
   * @return
   */
  public int getCompanyId() {
    return ((Integer) (getPerm(COMPANY_ID))).intValue();
  }

  /**
   * 
   * @param str
   */
  public void setCompanyId(int id) {
    setPerm(COMPANY_ID, Integer.valueOf(id));
  }

  /**
   * 
   * @return
   */
  public int getPostId() {
    return ((Integer) (getPerm(POST_ID))).intValue();
  }

  /**
   * 
   * @param str
   */
  public void setPostId(int id) {
    setPerm(POST_ID, Integer.valueOf(id));
  }

  /**
   * 
   * @return
   */
  public int getPositionId() {
    return ((Integer) (getPerm(POSITION_ID))).intValue();
  }

  /**
   * 
   * @param str
   */
  public void setPositionId(int id) {
    setPerm(POSITION_ID, Integer.valueOf(id));
  }

  /* Add　2011/2/14 Otomaru Start--- */
  /**
   * 
   * @param id
   * @return
   */
  public String getOfficeId(String id) {
    StringBuffer statementSel = new StringBuffer();
    
    statementSel.append(" SELECT office_id");
    statementSel.append("   FROM imw_t_office_calendar_map");
    statementSel.append("  WHERE user_id = '" + id + "'");
    String selectquery = statementSel.toString();
    
    DataContext selectdataContext = DatabaseOrmService.getInstance().getDataContext();
    SQLTemplate rawSelect = new SQLTemplate(ImwTOfficeCalendarMap.class, selectquery, true);
    rawSelect.setFetchingDataRows(true);
    List list = selectdataContext.performQuery(rawSelect);
    if (list.size() == 0 || list == null) {
      return "";
    }
    DataRow dataRow;
    dataRow = (DataRow) list.get(0);
    
    String OfficeId = ALEipUtils.getObjFromDataRow(dataRow, "office_id").toString();
    return OfficeId;
  }
//  
//  /**
//   * 
//   * @param str
//   */
//  public void setOfficeId(int id){
//    setPerm(OFFICE_ID,Integer.valueOf(id));
//  }
  /* Add　2011/2/14 Otomaru End----- */
  
  /**
   * 
   * @return
   */
  public String getFirstNameKana() {
    return (String) getPerm(FIRST_NAME_KANA);
  }

  /**
   * 
   * @param str
   */
  public void setFirstNameKana(String str) {
    setPerm(FIRST_NAME_KANA, str);
  }

  /**
   * 
   * @return
   */
  public String getLastNameKana() {
    return (String) getPerm(LAST_NAME_KANA);
  }

  /**
   * 
   * @param str
   */
  public void setLastNameKana(String str) {
    setPerm(LAST_NAME_KANA, str);
  }

  /**
   * 
   * @return byte[]
   */
  public byte[] getPhoto() {
    Object obj = getPerm(PHOTO);

    if (obj instanceof byte[])
      return (byte[]) obj;

    if (obj == null || "".equals(obj))
      return null;

    return ((String) obj).getBytes();
  }

  /**
   * 
   * @param v
   */
  public void setPhoto(byte[] b) {
    setPerm(PHOTO, b);
  }

  /**
   * @return
   */
  public int getCreatedUserId() {
    return ((Integer) (getPerm(CREATED_USER_ID))).intValue();
  }

  /**
   * @param id
   */
  public void setCreatedUserId(int id) {
    setPerm(CREATED_USER_ID, Integer.valueOf(id));
  }

  /**
   * @return
   */
  public int getUpdatedUserId() {
    return ((Integer) (getPerm(UPDATED_USER_ID))).intValue();
  }

  /**
   * @param id
   */
  public void setUpdatedUserId(int id) {
    setPerm(UPDATED_USER_ID, Integer.valueOf(id));
  }

  /**
   * @param d
   */
  public void setCreated(Date d) {
    setPerm(CREATED, d);
  }

  /**
   * @return
   */
  public Date getCreated() {
    return (Date) (getPerm(CREATED));
  }

  /**
   * @param d
   */
  public void setModified(Date d) {
    setPerm(MODIFIED, d);
  }

  /**
   * @return
   */
  public Date getModified() {
    return (Date) (getPerm(MODIFIED));
  }

  /**
   * 会社名を取得します。
   * 
   * @param id
   *            会社ID
   * @return 会社名
   */
  public String getCompanyName(int id) {
    Map companyMap = ALEipManager.getInstance().getCompanyMap();
    ALEipCompany company = (ALEipCompany) companyMap.get(Integer.valueOf(id));
    return company.getCompanyName().toString();
  }

  /**
   * 携帯電話の固有 ID を取得する．
   */
  public String getCelluarUId() {
    return (String) getPerm(CELLULAR_UID);
  }

  /**
   * 
   */
  public void setCelluarUId(String str) {
    setPerm(CELLULAR_UID, str);
  }
  
  /* Add　2010/8/24 muramoto Start--- */
  /**
   * 自家用車通勤フラグを取得する。
   */
  public int getCarCommutingFlag() {
    return ((Integer) getPerm(CAR_COMMUTING_FLAG)).intValue();
  }

  /**
   * 自家用車通勤フラグを登録する。 
   */
  public void setCarCommutingFlag(int flg) {
    setPerm(CAR_COMMUTING_FLAG, flg);
  }
  /* Add　2010/8/24 muramoto End--- */

  /* Add　2010/7/20 tou Start--- */
  
  /**
   * 退職フラグを取得する．
   */
  public int getRetireFlag() {
    return ((Integer) getPerm(RETIRE_FLAG)).intValue();
  }

  /**
   * 
   */
  public void setRetireFlag(int flg) {
    setPerm(RETIRE_FLAG, flg);
  }
  
  /**
   * パスワード有効期限を取得する．
   */
  public Date getPasswordEndDate() {
    return (Date) getPerm(PASSWORD_END_DATE);
  }

  /**
   * 
   */
  public void setPasswordEndDate(Date str) {
    setPerm(PASSWORD_END_DATE, str);
  }
  
  /**
   * 入社日を取得する．
   */
  public Date getEnterCompanyDate() {
    return (Date) getPerm(ENTER_COMPANY_DATE);
  }

  /**
   * 
   */
  public void setEnterCompanyDate(Date str) {
    setPerm(ENTER_COMPANY_DATE, str);
  }
  
  /**
   * 生年月日を取得する．
   */
  public Date getBirthday() {
    return (Date) getPerm(BIRTHDAY);
  }

  /**
   * 
   */
  public void setBirthday(Date str) {
    setPerm(BIRTHDAY, str);
  }
  /* Add　2010/7/20 tou End--- */
  
  /**
   * 最終アクセス時間を取得します。
   * 
   * @return
   */
  public String getLastAccessTime() {
    StringBuffer str = new StringBuffer();
    Calendar cal = Calendar.getInstance();
    cal.setTime(super.getLastAccessDate());
    return str.append(cal.get(Calendar.YEAR)).append("年").append(
        (cal.get(Calendar.MONTH) + 1)).append("月").append(
        cal.get(Calendar.DATE)).append("日 ").append(
        cal.get(Calendar.HOUR_OF_DAY)).append("時").append(
        cal.get(Calendar.MINUTE)).append("分").toString();
  }

  /* Add 2011/06/27 小濵 Start--- */
  /**
   * パスワード有効期限を過ぎていないかチェックを行います。。
   * 
   * @return
   */
  public int checkPasswordEndDate() {
    
    int passwordCheckDay = getPasswordCheckDay();
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MONTH, passwordCheckDay);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(cal.get(Calendar.YEAR),
        cal.get(Calendar.MONTH), 
        cal.get(Calendar.DAY_OF_MONTH),
        0, 
        0,
        0);
    Calendar passwordEndDate = Calendar.getInstance();
    passwordEndDate.setTime(getPasswordEndDate());
    passwordEndDate.set(passwordEndDate.get(Calendar.YEAR),
        passwordEndDate.get(Calendar.MONTH), 
        passwordEndDate.get(Calendar.DAY_OF_MONTH),
        0, 
        0,
        0);
    
    if(cal.before(passwordEndDate)){
      return (passwordCheckDay + 1);
    }else{
      long second_time = passwordEndDate.getTime().getTime() - cal.getTime().getTime();
      long day = (second_time / (1000 * 60 * 60 * 24)) + passwordCheckDay;
      return (int)day;
    }
  }
  public int getPasswordCheckDay() {
    try {

      int passwordCheckDay = 0;
      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
      SelectQuery query = new SelectQuery(ImwMHanyo.class);
      Expression exp = ExpressionFactory.matchExp(
          ImwMHanyo.PARENT_HANYO_ID_PROPERTY, 20);
      query.setQualifier(exp);
      List aList = dataContext.performQuery(query);

      if(aList != null && aList.size() > 0){
        for (int i = 0; i < aList.size(); i++) {
          ImwMHanyo record = (ImwMHanyo) aList.get(i);
          passwordCheckDay = Integer.parseInt(record.getValue());
        }
      }
      return passwordCheckDay;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return 0;
    }
  }
  /* Add 2011/06/27 小濵 End----- */

}
