/**
 * Copyright (c) 2003-2008 System Integrator Corporation.
 *                 All Rights Reserved.
 */
package jp.co.sint.servlet.mallmgr;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jp.co.sint.basic.SILogin;
import jp.co.sint.beans.mallmgr.UICmdtyPointListCond;
import jp.co.sint.beans.mallmgr.UICtgryListCond;
import jp.co.sint.beans.mallmgr.UIRegPointIndividual;
import jp.co.sint.config.SIConfig;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDBUtil;
import jp.co.sint.database.SIDatabaseConnection;
import jp.co.sint.database.SIDeleteRec;
import jp.co.sint.database.SIDuplicateKeyException;
import jp.co.sint.database.SIInsertRec;
import jp.co.sint.database.SIModifyRec;
import jp.co.sint.servlet.SIServlet;
import jp.co.sint.tools.SICustomError;
import jp.co.sint.tools.SICustomErrors;
import jp.co.sint.tools.SIErrorFactory;
import jp.co.sint.tools.SIHTMLUtil;

import org.apache.log4j.Category;
import jp.co.sint.tools.SIURLParameter;

public class SIRegCmdtyPointSrv extends SIServlet {
  // ログ用のインスタンスの生成
  
  /**
   * <b>doUpdate</b>
   * HTTP リクエストの処理
   * @param  request　リクエスト
   * @param  response
   * @return なし
   * @throws ServletException
   * @throws IOException
   */
  public void doUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    SILogin manLogin = SIHTMLUtil.getLogin(request);
    if (!manLogin.isLogin()) {
      forwardKey(request, response, "webshop.jsp.manager.login");
      return;
    }
    
    HttpSession session = request.getSession(true);// セッションの取得
    SIDatabaseConnection databaseConnection = new SIDatabaseConnection();// DBへのコネクションの作成
    SIURLParameter urlParam = new SIURLParameter(request);
    
    try {
      String actionName = this.getActionName(urlParam);// 画面からのアクション
      String editMode = this.getEditMode(urlParam);// DBへの編集モード

      UICmdtyPointListCond pointList = new UICmdtyPointListCond();
      
      if (SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName)) {// 一覧と検索などの画面
        // データの取得とデータのチェック
        pointList = new UICmdtyPointListCond(request, urlParam);
        pointList.validate(request);
        session.setAttribute(SIConfig.SISESSION_MAN_CMDTYPOINT_LIST_NAME, pointList);
        forwardKey(request, response, "webshop.jsp.manager.cmdtypoint.list");
      } else if (SIConfig.SIACTION_DETAIL.equalsIgnoreCase(actionName)) {// 明細画面
        UIRegPointIndividual regPoint = new UIRegPointIndividual(request, urlParam);
        regPoint.reset(databaseConnection.getConnection());
        session.setAttribute(SIConfig.SISESSION_MAN_CMDTYPOINT_EDIT_NAME, regPoint);
        forwardKey(request, response, "webshop.jsp.manager.cmdtypoint.edit");
      } else if (SIConfig.SIACTION_BACK.equalsIgnoreCase(actionName)) {// 元の画面に戻る
        forwardKey(request, response, "webshop.jsp.manager.cmdtypoint.list");
      } else if (SIConfig.SIACTION_RESERVE.equalsIgnoreCase(actionName)){ //ポイントルールの予約
        UIRegPointIndividual regPoint = new UIRegPointIndividual(request, urlParam);
        regPoint.reset(databaseConnection.getConnection());
        if(regPoint.validateInsertBonus(request, databaseConnection.getConnection())){
          try {
            insertBonusData(databaseConnection.getConnection(), regPoint, manLogin.getUserCode());
            request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.insert"));
            try {
              databaseConnection.getConnection().commit();
            } catch (SQLException sqle) {}
            regPoint.clear();
          } catch (SIDuplicateKeyException sqle) {
            try {
              databaseConnection.getConnection().rollback();
            } catch (SQLException ee) {}
            sqle.printStackTrace();
            SICustomErrors errors = new SICustomErrors();
            errors.addError(new SICustomError("database.execute.error"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
          } catch (SIDBAccessException sqle) {
            try {
              databaseConnection.getConnection().rollback();
            } catch (SQLException ee) {}
            sqle.printStackTrace();
            SICustomErrors errors = new SICustomErrors();
            errors.addError(new SICustomError("database.execute.error"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
          }
        }
        session.setAttribute(SIConfig.SISESSION_MAN_CMDTYPOINT_EDIT_NAME, regPoint);
        forwardKey(request, response, "webshop.jsp.manager.cmdtypoint.edit");
      } else if (SIConfig.SIACTION_DELETE.equalsIgnoreCase(actionName)){ //予約中ポイントルールのキャンセル
        UIRegPointIndividual regPoint = new UIRegPointIndividual(request, urlParam);
        regPoint.reset(databaseConnection.getConnection());
        try {
          deleteBonusData(databaseConnection.getConnection(), regPoint);
          request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.delete"));
          try {
            databaseConnection.getConnection().commit();
          } catch (SQLException sqle) {}
          regPoint.clear();
        } catch (SIDBAccessException sqle) {
          try {
            databaseConnection.getConnection().rollback();
          } catch (SQLException ee) {}
          sqle.printStackTrace();
          SICustomErrors errors = new SICustomErrors();
          errors.addError(new SICustomError("database.execute.error"));
          request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
        }
        session.setAttribute(SIConfig.SISESSION_MAN_CMDTYPOINT_EDIT_NAME, regPoint);
        forwardKey(request, response, "webshop.jsp.manager.cmdtypoint.edit");
      } else if (SIConfig.SIACTION_PREVIEW.equalsIgnoreCase(actionName)){ //執行中ポイントルールの選択
        UIRegPointIndividual regPoint = new UIRegPointIndividual(request, urlParam);
        regPoint.reset(databaseConnection.getConnection());
        regPoint.initDetail(request, databaseConnection.getConnection());
        session.setAttribute(SIConfig.SISESSION_MAN_CMDTYPOINT_EDIT_NAME, regPoint);
        forwardKey(request, response, "webshop.jsp.manager.cmdtypoint.edit");
      } else if (SIConfig.SIACTION_REGIST.equalsIgnoreCase(actionName)){ //執行中ポイントルールの終了期間変更
        UIRegPointIndividual regPoint = new UIRegPointIndividual(request, urlParam);
        regPoint.reset(databaseConnection.getConnection());
        if(regPoint.validateUpdateBonus(request, databaseConnection.getConnection())){
          try {
            updateBonusData(databaseConnection.getConnection(), regPoint, manLogin.getUserCode());
            request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.modify"));
            try {
              databaseConnection.getConnection().commit();
            } catch (SQLException sqle) {}
            regPoint.clear();
          } catch (SIDuplicateKeyException sqle) {
            try {
              databaseConnection.getConnection().rollback();
            } catch (SQLException ee) {}
            sqle.printStackTrace();
            SICustomErrors errors = new SICustomErrors();
            errors.addError(new SICustomError("database.execute.error"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
          } catch (SIDBAccessException sqle) {
            try {
              databaseConnection.getConnection().rollback();
            } catch (SQLException ee) {}
            sqle.printStackTrace();
            SICustomErrors errors = new SICustomErrors();
            errors.addError(new SICustomError("database.execute.error"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
          }
        }
        session.setAttribute(SIConfig.SISESSION_MAN_CMDTYPOINT_EDIT_NAME, regPoint);
        forwardKey(request, response, "webshop.jsp.manager.cmdtypoint.edit");
      }
    } catch (SQLException e) {
      e.printStackTrace();
      throw new ServletException();
    } catch (NamingException e) {
      e.printStackTrace();
      throw new ServletException();
    } finally {
      databaseConnection.close();
    }
    
  }
  private void insertBonusData(Connection lConnection, UIRegPointIndividual regPoint, String userCode) throws SIDuplicateKeyException, SIDBAccessException {
    SIInsertRec lInsertRec = new SIInsertRec("BonusPointIndividualTbl");
    lInsertRec.add("CmdtyCode", regPoint.getCmdtyCode());
    lInsertRec.add("IndividualCode", regPoint.getIndividualCode());
    lInsertRec.add("BonusPointRate", regPoint.getBonusPointRate());
    lInsertRec.add("BonusFromDate", regPoint.getBonusFromDate());
    lInsertRec.add("BonusToDate", regPoint.getBonusToDate());
    lInsertRec.add("InsertUser", userCode);
    lInsertRec.execute(lConnection);
  }
  
  private void updateBonusData(Connection lConnection, UIRegPointIndividual regPoint, String userCode) throws SIDuplicateKeyException, SIDBAccessException {
    SIModifyRec lRec = new SIModifyRec("BonusPointIndividualTbl");
    
    try {
      lRec.addCondition("CmdtyCode", regPoint.getCmdtyCode());
      lRec.addCondition("IndividualCode", regPoint.getIndividualCode());
      lRec.addCondition("BonusFromDate", regPoint.getBonusFromDate());// ボーナス開始日
      lRec.add("BonusToDate", regPoint.getBonusToDate());// ボーナス終了日
      lRec.add("UpdateUser", userCode);
      
      lRec.execute(lConnection);
      
    } catch (SIDuplicateKeyException sqle) {
      throw new SIDBAccessException(sqle);
    }
  }
  
  private void deleteBonusData(Connection lConnection, UIRegPointIndividual regPoint) throws SIDBAccessException {
    String sql = "DELETE FROM bonuspointindividualtbl WHERE bonusfromdate > current_date AND individualcode="+SIDBUtil.SQL2Str(regPoint.getIndividualCode());
    SIDBUtil.execSQL(lConnection, sql);
  }
  
  public void destroy() {}
}
