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

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

import org.apache.cayenne.DataObjectUtils;
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.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;

import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.cayenne.om.portlet.ImwMClient;
import com.aimluck.eip.cayenne.om.portlet.ImwMHanyo;
import com.aimluck.eip.cayenne.om.portlet.ImwMItem;
import com.aimluck.eip.cayenne.om.portlet.ImwMItemCategory;
import com.aimluck.eip.cayenne.om.portlet.ImwMItemSubcategory;
import com.aimluck.eip.cayenne.om.portlet.ImwTAccount;
import com.aimluck.eip.cayenne.om.portlet.ImwTAccountPlan;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.util.ALEipUtils;
import com.aimluck.eip.cashflow.AccountPlanResultData;

/**
 * 入出金予定のユーティリティクラスです。 <BR>
 * 
 */
public class AccountPlanUtils {

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

  /** グループによる表示切り替え用変数の識別子 */
  public static final String SHOW_LIST_NAME = "showList_name";

  /** ユーザによる表示切り替え用変数の識別子 */
  public static final String TARGET_USER_ID = "target_user_id";

  /** 期限状態（期限前） */
  public static final int LIMIT_STATE_BEFORE = -1;

  /** 期限状態（期限当日） */
  public static final int LIMIT_STATE_TODAY = 0;

  /** 期限状態（期限後） */
  public static final int LIMIT_STATE_AFTER = 1;

  /**
   * 入出金予定 オブジェクトモデルを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @param isJoin
   *            カテゴリテーブルをJOINするかどうか
   * @return
   */
  public static ImwTAccountPlan getImwTAccountPlan(RunData rundata, Context context,
      boolean isJoin) throws ALPageNotFoundException,
    ALDBErrorException {
      String planid = ALEipUtils.getTemp(rundata, context,
          ALEipConstants.ENTITY_ID);
    try {
      if (planid == null || Integer.valueOf(planid) == null) {
        // 入出金予定 IDが空の場合
        logger.debug("[AccountPlanUtils] Empty ID...");
        return null;
      }

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

      SelectQuery query = new SelectQuery(ImwTAccountPlan.class);
      Expression exp1 = ExpressionFactory.matchDbExp(
          ImwTAccountPlan.ACCOUNT_ID_PK_COLUMN, Integer.valueOf(planid));
      query.setQualifier(exp1);

      List accountPlans = dataContext.performQuery(query);

      if (accountPlans == null || accountPlans.size() == 0) {
        // 指定した入出金予定 IDのレコードが見つからない場合
        throw new ALPageNotFoundException();
      }

      ImwTAccountPlan plan = ((ImwTAccountPlan) accountPlans.get(0));
//      
//      // 入出金区分
//      SelectQuery typeQuery = new SelectQuery(ImwMItemCategory.class);
//
//      Expression exp3 = ExpressionFactory.matchDbExp(
//          ImwMItemCategory.ITEM_CATEGORY_ID_PK_COLUMN, plan.getImwMItem().getItemCategoryId());
//      typeQuery.setQualifier(exp3);
//      List typelist = dataContext.performQuery(typeQuery);
//
//      ImwMItemCategory imwmitemcategory = (ImwMItemCategory)typelist.get(0);
//      rd.setAccountType(imwmitemcategory.getAccountClass().longValue());
//      
//      accountPlans.add(rd);

      return plan;
    } catch (Exception ex) {
      // TODO: エラー処理
      logger.error("[AccountPlanUtils]", ex);
      throw new ALDBErrorException();

    }
  }
  /**
   * 入出金予定 オブジェクトモデルを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @param isJoin
   *            カテゴリテーブルをJOINするかどうか
   * @return
   */
  public static ImwTAccount getImwTAccount(RunData rundata, Context context,
      boolean isJoin) throws ALPageNotFoundException,
    ALDBErrorException {
      String accountid = ALEipUtils.getTemp(rundata, context,
          ALEipConstants.ENTITY_ID);
    try {
      if (accountid == null || Integer.valueOf(accountid) == null) {
        // 入出金 IDが空の場合
        logger.debug("[AccountPlanUtils] Empty ID...");
        return null;
      }

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

      SelectQuery query = new SelectQuery(ImwTAccount.class);
      Expression exp1 = ExpressionFactory.matchDbExp(
          ImwTAccount.ACCOUNT_ID_PK_COLUMN, Integer.valueOf(accountid));
      query.setQualifier(exp1);

      List accounts = dataContext.performQuery(query);

      if (accounts == null || accounts.size() == 0) {
        // 指定した入出金予定 IDのレコードが見つからない場合
        throw new ALPageNotFoundException();
      }

      ImwTAccount account = ((ImwTAccount) accounts.get(0));
      return account;
    } catch (Exception ex) {
      // TODO: エラー処理
      logger.error("[AccountPlanUtils]", ex);
      throw new ALDBErrorException();

    }
  }
//
//  /**
//   * 公開 Todo オブジェクトモデルを取得します。 <BR>
//   * 
//   * @param rundata
//   * @param context
//   * @param isJoin
//   *            カテゴリテーブルをJOINするかどうか
//   * @return
//   */
//  public static EipTTodo getEipTPublicTodo(RunData rundata, Context context,
//      boolean isJoin) {
//    String todoid = ALEipUtils.getTemp(rundata, context,
//        ALEipConstants.ENTITY_ID);
//    try {
//      if (todoid == null || Integer.valueOf(todoid) == null) {
//        // Todo IDが空の場合
//        logger.debug("[AccountPlanUtils] Empty ID...");
//        return null;
//      }
//
//      DataContext dataContext = DatabaseOrmService.getInstance()
//          .getDataContext();
//      Expression exp = ExpressionFactory.matchDbExp(EipTTodo.TODO_ID_PK_COLUMN,
//          todoid);
//      exp
//          .andExp(ExpressionFactory
//              .matchExp(EipTTodo.PUBLIC_FLAG_PROPERTY, "T"));
//      SelectQuery query = new SelectQuery(EipTTodo.class, exp);
//
//      List todos = dataContext.performQuery(query);
//
//      if (todos == null || todos.size() == 0) {
//        // 指定したTodo IDのレコードが見つからない場合
//        logger.debug("[Todo] Not found ID...");
//        return null;
//      }
//      return ((EipTTodo) todos.get(0));
//    } catch (Exception ex) {
//      logger.error("Exception", ex);
//      return null;
//    }
//  }

//  /**
//   * 原価計算カテゴリ オブジェクトモデルを取得します。 <BR>
//   * 
//   * @param rundata
//   * @param context
//   * @return
//   */
//  public static ImwTAccountPlan getImwTAccountPlan(DataContext dataContext,
//      Long account_id) {
//    try {
//      ImwTAccountPlan accountplan = (ImwTAccountPlan) DataObjectUtils
//          .objectForPK(dataContext, ImwTAccountPlan.class, account_id);
//      return accountplan;
//    } catch (Exception ex) {
//      logger.error("Exception", ex);
//      return null;
//    }
//  }
  /**
   * 科目 オブジェクトモデルを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static ImwMItem getImwMItem(DataContext dataContext,Long item_id) {
    try {
      ImwMItem item = (ImwMItem) DataObjectUtils
          .objectForPK(dataContext, ImwMItem.class, item_id);
      return item;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }
  
  /**
   * 取引先 オブジェクトモデルを取得します。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static ImwMClient getImwMClient(DataContext dataContext,
      Long client_id) {
    try {
      ImwMClient client = (ImwMClient) DataObjectUtils
          .objectForPK(dataContext, ImwMClient.class, client_id);
      return client;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }
  
  /**
   * カテゴリ一覧を取得する。 <BR>
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static List loadCategoryList(RunData rundata, Context context) {
    try {
      // カテゴリ一覧
      List categoryList = new ArrayList();

      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
      SelectQuery query = new SelectQuery(ImwMItemCategory.class);
      List aList = dataContext.performQuery(query);

//      int size = aList.size();
//      for (int i = 0; i < size; i++) {
//        ImwMItemCategory record = (ImwMItemCategory) aList.get(i);
//        ItemCategoryResultData rd = new ItemCategoryResultData();
//        rd.initField();
//        rd.setCategoryId(record.getItemCategoryId().longValue());
//        rd.setCategoryName(record.getItemCategoryName());
//        List subCats = new ArrayList();
//        for(Object obj : record.getImwMItemSubcategory()){
//          ImwMItemSubcategory subcat = (ImwMItemSubcategory)obj;
//          ItemSubCategoryResultData rdsubcat = new ItemSubCategoryResultData();
//          rdsubcat.initField();
//          rdsubcat.setSubCategoryId(subcat.getItemSubcategoryId());
//          rdsubcat.setSubCategoryName(subcat.getItemSubcategoryName());
//          subCats.add(rdsubcat);
//        }
//        rd.setSubCategoryList(subCats);
//        categoryList.add(rd);
//      }
//
//      return categoryList;
      return aList;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }
  
  /**
   * サブカテゴリ一覧を取得する。 <BR>
   * 
   * @param num
   * @return
   */
  public static List loadSubCategoryList(RunData rundata, Context context) {
    try {
      List subCategoryList = new ArrayList();

      Integer categoryId = rundata.getParameters().getInteger("category_id");

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

      SelectQuery query = new SelectQuery(ImwMItemCategory.class);
      Expression exp1 = ExpressionFactory.matchExp(
          ImwMItemCategory.DISABLED_PROPERTY, "F");
      query.setQualifier(exp1);
      Expression exp2 = ExpressionFactory.matchDbExp(
          ImwMItemCategory.ITEM_CATEGORY_ID_PK_COLUMN, Integer.valueOf(categoryId));
      query.andQualifier(exp2);
      List aList = dataContext.performQuery(query);

      if (aList == null || aList.size() == 0 ) {
        return null;
      }
      
      ImwMItemCategory record1 = (ImwMItemCategory) aList.get(0);
      AccountPlanResultData rd1 = new AccountPlanResultData();
      List subCateList = record1.getImwMItemSubcategory();

      subCategoryList = new ArrayList();

      int size = subCateList.size();
      for (int i = 0; i < size; i++) {
        ImwMItemSubcategory record = (ImwMItemSubcategory) subCateList.get(i);
        AccountPlanResultData rd = new AccountPlanResultData();
        rd.initField();
        rd.setSubCategoryId(record.getItemSubcategoryId());
        rd.setSubCategoryName(record.getItemSubcategoryName());

        subCategoryList.add(rd);
      }
      return subCategoryList;
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return null;
    }
  }
  
  /**
   * 
   * @return
   */
  public static Date getEmptyDate() {
    Calendar cal = Calendar.getInstance();
    cal.set(9999, 11, 31);
    return cal.getTime();
  }

  /**
   * 
   * @param date
   * @return
   */
  public static boolean isEmptyDate(Date date) {
    if (date == null)
      return true;
    return date.getYear() == 8099;
  }

  /**
   * 表示切り替えで指定したグループ ID を取得する．
   * 
   * @param rundata
   * @param context
   * @return
   */
  public static String getShowListName(RunData rundata, Context context) {
    String show_list_name = null;
    String idParam = rundata.getParameters().getString(SHOW_LIST_NAME);
    show_list_name = ALEipUtils.getTemp(rundata, context, SHOW_LIST_NAME);
    if (idParam == null && show_list_name == null) {
      ALEipUtils.setTemp(rundata, context, SHOW_LIST_NAME, "all");
      show_list_name = "all";
    } else if (idParam != null && idParam == "seikyuList") {
      ALEipUtils.setTemp(rundata, context, SHOW_LIST_NAME, idParam);
      show_list_name = idParam;
    }
    return show_list_name;
  }

  /**
   * 3 桁でカンマ区切りした文字列を取得する．
   * 
   * @param money
   * @return
   */
  public static String translateMoneyStr(String money) {
    if (money == null || money.length() == 0)
      return money;

    StringBuffer sb = new StringBuffer();
    int len = money.length();
    int count = len / 3;
    int del = len % 3;
    sb.append(money.substring(0, del));
    if (count > 0) {
      if (len > 3 && del != 0) {
        sb.append(",");
      }
      for (int i = 0; i < count; i++) {
        sb.append(money.substring(del + 3 * i, del + 3 * i + 3));
        if (i != count - 1) {
          sb.append(",");
        }
      }
    }
    return sb.toString();
  }

  static public ImwMHanyo getHanyoByKey(int parentId, String value){
    DataContext dataContext = DatabaseOrmService.getInstance()
      .getDataContext();
    SelectQuery query = new SelectQuery(ImwMHanyo.class);

    Expression exp = ExpressionFactory.matchExp(
        ImwMHanyo.PARENT_HANYO_ID_PROPERTY, parentId);
    query.setQualifier(exp);

    Expression andexp = ExpressionFactory.matchExp(
        ImwMHanyo.VALUE_PROPERTY, value);
    query.andQualifier(andexp);
  
    List list = dataContext.performQuery(query);
    
    if(list.size() == 0){
      return null;
    }
    
    return (ImwMHanyo)list.get(0);
  }
}

