/**
 * Copyright (c) 2003-2004 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.UIRegWrapping;
import jp.co.sint.config.SIConfig;
import jp.co.sint.database.SIDBAccessException;
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.database.SISpcType;
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.SIFileUtil;
import jp.co.sint.tools.SIHTMLUtil;

import org.apache.log4j.Category;
import jp.co.sint.tools.SIURLParameter;//7.1.1 ST0236 追加

/**
 * @version $Id: SIRegWrappingSrv.java,v 1.0 2003/8/25 Exp $
 * @author  Arai
 * <br>Description:
 * <p>History</p>
 * <p>Author&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Reason</p>
 *  ============&nbsp;&nbsp;&nbsp;==========&nbsp;&nbsp;===========================<br>
 * Arai   2003/8/25 14:25:29  Original
 */
public class SIRegWrappingSrv extends SIServlet {

  //ログ用のインスタンスの生成
  private static Category log = Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);

  /**
   * <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);//セッションの取得

    UIRegWrapping regList = new UIRegWrapping();
    SIDatabaseConnection databaseConnection = new SIDatabaseConnection();
	SIURLParameter urlParam = new SIURLParameter(request);//7.1.1 ST0236 追加
    try{
      Connection connection= databaseConnection.getConnection();

	  String actionName=this.getActionName(urlParam);//画面からのアクション	//7.1.1 ST0236 修正ン
	  String editMode = this.getEditMode(urlParam); //DBへの編集モード	//7.1.1 ST0236 修正

      if (SIConfig.SIACTION_NEW.equalsIgnoreCase(actionName)) {
        forwardKey(request, response, "webshop.jsp.manager.wrapping.list");
      } else if (SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName)) {
        //一覧と検索などの画面
		regList.init(request,urlParam);//7.1.1 ST0236 修正
        session.setAttribute(SIConfig.SISESSION_MAN_WRAPPING_LIST_NAME, regList);
        forwardKey(request, response, "webshop.jsp.manager.wrapping.list");
      } else {
        //データの取得
		regList.init(request,urlParam);//7.1.1 ST0236 修正

        //データのチェック
        if (regList.validate(request, connection) == false) {
          errorSetting(request, regList, editMode);
          forwardKey(request,response,"webshop.jsp.manager.wrapping.list");
        } else {
          session.setAttribute(SIConfig.SISESSION_MAN_WRAPPING_LIST_NAME, regList);
          try {
            if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_INSERT)){
              insertTableData(connection,regList);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.insert"));
              try {connection.commit();} catch (SQLException sqle) {}
            }else if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_UPDATE)){
              updateTableData(connection,regList);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.modify"));
              try {connection.commit();} catch (SQLException sqle) {}
            }else if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_DELETE)){
              deleteTableData(regList, connection);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.delete"));
              try {connection.commit();} catch (SQLException sqle) {}
            }else{
              log.error("no known edit mode.editMode=" + editMode);
            }
            forwardKey(request, response, "webshop.jsp.manager.wrapping.result");
          } catch (SIDuplicateKeyException sqle) {
            try {connection.rollback();} catch (SQLException e) {}
            SICustomErrors errors = new SICustomErrors();
            errors.addError(new SICustomError("database.insert.duplicate"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
            errorSetting(request, regList, editMode);
            forwardKey(request, response, "webshop.jsp.manager.wrapping.edit");
          } catch (SIDBAccessException sqle) {
            try {connection.rollback();} catch (SQLException e) {}
            SICustomErrors errors = new SICustomErrors();
            errors.addError(new SICustomError("database.execute.error"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
            forwardKey(request, response, "webshop.jsp.manager.wrapping.edit");
          }
        }
      }
    }catch (SQLException e){
      e.printStackTrace();
      throw new ServletException();
    }catch (NamingException e){
      e.printStackTrace();
      throw new ServletException();
    }finally{
      databaseConnection.close();
    }
  }

  /**
   * errorSetting
   * エラー発生時の入力値を保持します。
   * @param　HttpServletRequest , UIRegWrapping , String
   * @return
   * @throws
   */
  public void errorSetting(HttpServletRequest request, UIRegWrapping regList, String editMode) {
    HttpSession session=request.getSession(true);//セッションの取得

    if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_INSERT)) {
      regList.setActionNameTxt(SIConfig.SIACTION_NEW);
    } else if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_UPDATE)) {
      regList.setActionNameTxt(SIConfig.SIACTION_LIST);
    }
    session.setAttribute(SIConfig.SISESSION_MAN_WRAPPING_LIST_NAME, regList);
    request.setAttribute("remodify", SIConfig.SIACTION_REMODIFY);
  }

  /**
   * insertTableData
   * データベースにレコードを挿入します。
   * @param  Connection
   * @param  UIRegWrapping
   * @return  なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public static void insertTableData( Connection connection,UIRegWrapping regList) throws SIDuplicateKeyException, SIDBAccessException {

    SISpcType lSpcType = new SISpcType();
    SIInsertRec lRec = new SIInsertRec("wrappingmtbl");
    lRec.add("shopcode", regList.getShopCode());
    lRec.add("wrappingcode", regList.getWrappingCode());
    lRec.add("wrappingname", regList.getWrappingName());
    lRec.add("description", regList.getDescription());
    lRec.add("price", regList.getPrice());
    lRec.add("taxFlg", regList.getTaxFlg());
    log.debug("insert sql=" + lRec.getSQL());
    lRec.execute(connection);

  }

  /**
   * updateTableData
   * データベースにレコードを修正します。
   * @param Connection
   * @param UIRegWrapping
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public static void updateTableData(Connection connection,UIRegWrapping regList) throws SIDuplicateKeyException, SIDBAccessException {

    SISpcType lSpcType = new SISpcType();
    SIModifyRec lRec = new SIModifyRec("wrappingmtbl");
    lRec.addCondition("shopcode", regList.getShopCode());
    lRec.addCondition("wrappingcode", regList.getWrappingCode());
    lRec.add("wrappingname", regList.getWrappingName());
    lRec.add("description", regList.getDescription());
    lRec.add("price", regList.getPrice());
    lRec.add("taxFlg", regList.getTaxFlg());

    log.debug("update sql=" + lRec.getSQL());
    lRec.execute(connection);
  }
  /**
  * deleteTableData
  * データを削除します。
  * @param UIRegWrapping
  * @param Connection
  * @return なし
  * @throws SIDuplicateKeyException
  * @throws SIDBAccessException
  */
  public void deleteTableData(UIRegWrapping regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {

	//画像を削除する。
	SIFileUtil fileUtil = new SIFileUtil(this.context,regList.getShopCode());
	fileUtil.wrappingImgDel(regList.getWrappingCode());

	//データを削除
    SIDeleteRec lDeleteRec = new SIDeleteRec();
    lDeleteRec = new SIDeleteRec();
    lDeleteRec.setTableName("wrappingmtbl");
    lDeleteRec.addCondition("shopcode", regList.getShopCode());
    lDeleteRec.addCondition("wrappingcode", regList.getWrappingCode());

    //データの更新
    log.debug("delete sql=" + lDeleteRec.getSQL());
    lDeleteRec.execute(connection);
  }

  public void destroy() {
  }

}
