/*
 * 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.hanyo;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.cayenne.ObjectId;
import org.apache.cayenne.access.DataContext;
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.ALNumberField;
import com.aimluck.commons.field.ALStringField;
import com.aimluck.eip.hanyo.util.HanyoUtils;
import com.aimluck.eip.cayenne.om.portlet.ImwMHanyo;
import com.aimluck.eip.common.ALAbstractFormData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.modules.actions.common.ALAction;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.util.ALEipUtils;

/**
 * 汎用マスタのフォームデータを管理するクラスです。 <BR>
 * 
 */
public class HanyoFormData extends ALAbstractFormData {

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

  private String org_id;

  private DataContext dataContext;

  private ALNumberField hanyoId;

  private ALNumberField parentHanyoId;

  private ALStringField hanyokubunnm;

  private ALStringField disabled;

  private ALStringField value;

  private ALStringField notDelete;

  private ArrayList hanyoList;

  /**
   * 初期化します。
   * 
   * @param action
   * @param rundata
   * @param context
   * @see com.aimluck.eip.common.ALAbstractFormData#init(com.aimluck.eip.modules.actions.common.ALAction,
   *      org.apache.turbine.util.RunData, org.apache.velocity.context.Context)
   */
  public void init(ALAction action, RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {
    super.init(action, rundata, context);

    org_id = DatabaseOrmService.getInstance().getOrgId(rundata);

    dataContext = DatabaseOrmService.getInstance().getDataContext();
  }

  /**
   * 各フィールドを初期化します。 <BR>
   * 
   * @see com.aimluck.eip.common.ALData#initField()
   */
  public void initField() {

    hanyoId = new ALNumberField();

    parentHanyoId = new ALNumberField();
    parentHanyoId.setFieldName("親汎用名");

    hanyokubunnm = new ALStringField();
    hanyokubunnm.setFieldName("汎用名");
    hanyokubunnm.setTrim(true);

    disabled = new ALStringField();
    disabled.setTrim(true);

    value = new ALStringField();
    value.setFieldName("値");
    value.setTrim(true);

    notDelete = new ALStringField();
    notDelete.setTrim(true);

    hanyoList = new ArrayList();

  }

  /**
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return
   * @see com.aimluck.eip.common.ALAbstractFormData#setFormData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context, java.util.ArrayList)
   */
  protected boolean setFormData(RunData rundata, Context context,
      ArrayList msgList) throws ALPageNotFoundException, ALDBErrorException {
    boolean res = super.setFormData(rundata, context, msgList);
    try {
      if (res) {

        hanyoList.addAll(HanyoUtils.getHanyoList());

        return true;

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

  /**
   * 各フィールドに対する制約条件を設定します。 <BR>
   * 
   * @see com.aimluck.eip.common.ALAbstractFormData#setValidator()
   */
  protected void setValidator() {

    parentHanyoId.setNotNull(true);
    // Del 2011/2/7 aseda 
    // parentHanyoId.limitMaxValue(10);

    hanyokubunnm.setNotNull(true);
    hanyokubunnm.limitMaxLength(30);

    value.setNotNull(true);
    value.limitMaxLength(30);

  }

  /**
   * フォームに入力されたデータの妥当性検証を行います。 <BR>
   * 
   * @param msgList
   * @return
   * @see com.aimluck.eip.common.ALAbstractFormData#validate(java.util.ArrayList)
   */
  protected boolean validate(ArrayList msgList) {

    parentHanyoId.validate(msgList);
    hanyokubunnm.validate(msgList);
    value.validate(msgList);
    return (msgList.size() == 0);

  }

  /**
   * 『ユーザー』を読み込みます。 <BR>
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return
   * @see com.aimluck.eip.common.ALAbstractFormData#loadFormData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context, java.util.ArrayList)
   */
  protected boolean loadFormData(RunData rundata, Context context,
      ArrayList msgList) {
    try {

      hanyoList.addAll(HanyoUtils.getHanyoList());

      ImwMHanyo imwMHanyo = HanyoUtils.getImwMHanyo(rundata, context);

      hanyoId.setValue(imwMHanyo.getHanyoId());
      parentHanyoId.setValue(imwMHanyo.getParentHanyoId());
      hanyokubunnm.setValue(imwMHanyo.getHanyokubunnm());
      disabled.setValue(imwMHanyo.getDisabled());
      value.setValue(imwMHanyo.getValue());
      notDelete.setValue(imwMHanyo.getNotDelete());

      return true;
    } catch (Exception e) {
      logger.error("Exception", e);
      return false;
    }
  }

  /**
   * 『ユーザー』を追加します。 <BR>
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return
   * @see com.aimluck.eip.common.ALAbstractFormData#insertFormData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context, java.util.ArrayList)
   */
  protected boolean insertFormData(RunData rundata, Context context,
      ArrayList msgList) {

    parentHanyoId.validate(msgList);
    hanyokubunnm.validate(msgList);
    value.validate(msgList);
    try {

      if (dataContext == null) {
        dataContext = DatabaseOrmService.getInstance().getDataContext();
      }
      ImwMHanyo record = (ImwMHanyo) dataContext
          .createAndRegisterNewObject(ImwMHanyo.class);

      record.setParentHanyoId((int)parentHanyoId.getValue());

      record.setHanyokubunnm(hanyokubunnm.getValue());

      record.setValue(value.getValue());

      record.setDisabled("F");

      if ("1".equals(notDelete.getValue())) {
        record.setNotDelete("1");
      } else {
        record.setNotDelete("0");
      }

      record.setCreateUserId(ALEipUtils.getUserId(rundata));

      record.setUpdateUserId(ALEipUtils.getUserId(rundata));

      Date now = new Date();

      record.setCreateDate(now);

      record.setUpdateDate(now);

      dataContext.commitChanges();

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

  /**
   * 『ユーザー』を更新します。 <BR>
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return
   * @see com.aimluck.eip.common.ALAbstractFormData#updateFormData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context, java.util.ArrayList)
   */
  protected boolean updateFormData(RunData rundata, Context context,
      ArrayList msgList) {
    boolean res = true;
    try {
      ImwMHanyo record = HanyoUtils.getImwMHanyo(rundata, context);
      if (record == null)
        return false;

      record.setParentHanyoId((int)parentHanyoId.getValue());

      record.setHanyokubunnm(hanyokubunnm.getValue());

      record.setValue(value.getValue());

      if ("1".equals(notDelete.getValue())) {
        record.setNotDelete("1");
      } else {
        record.setNotDelete("0");
      }

      record.setUpdateUserId(ALEipUtils.getUserId(rundata));

      Date now = new Date();

      record.setUpdateDate(now);

      dataContext.commitChanges();

    } catch (Exception e) {
      logger.error("Exception", e);
      res = false;
    }
    return res;
  }

  /**
   * 『ユーザー』を削除します。 <BR>
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return
   * @see com.aimluck.eip.common.ALAbstractFormData#deleteFormData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context, java.util.ArrayList)
   */
  protected boolean deleteFormData(RunData rundata, Context context,
      ArrayList msgList) {

    try {
      String hanyo_id = ALEipUtils.getTemp(rundata, context,
          ALEipConstants.ENTITY_ID);

      if (hanyo_id == null)
        return false;

      // 汎用マスタを論理削除
      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
      ObjectId oid_user = new ObjectId("ImwMHanyo",
          ImwMHanyo.HANYO_ID_PK_COLUMN, hanyo_id);
      ImwMHanyo imwMHanyo = (ImwMHanyo) dataContext.refetchObject(oid_user);

      imwMHanyo.setDisabled("T");

      imwMHanyo.setUpdateUserId(ALEipUtils.getUserId(rundata));

      Date now = new Date();

      imwMHanyo.setUpdateDate(now);
      dataContext.commitChanges();

      return true;
    } catch (Exception e) {
      logger.error("Exception", e);
      return false;
    }
  }

  /**
   * 指定したchar型文字が記号であるかを判断します。
   * 
   * @param ch
   * @return
   */
  protected boolean isSymbol(char ch) {
    byte[] chars;

    try {
      chars = (Character.valueOf(ch).toString()).getBytes("shift_jis");
    } catch (UnsupportedEncodingException ex) {
      return false;
    }

    if (chars == null || chars.length == 2 || Character.isDigit(ch)
        || Character.isLetter(ch)) {
      return false;
    } else {
      return true;
    }

  }

  public ALNumberField getHanyoId() {
    return hanyoId;
  }

  public ALNumberField getParentHanyoId() {
    return parentHanyoId;
  }

  public ALStringField getHanyokubunnm() {
    return hanyokubunnm;
  }

  public ALStringField getValue() {
    return value;
  }

  public ALStringField getNotDelete() {
    return notDelete;
  }

  public List getHanyoList() {
    return hanyoList;
  }
}
