/**
 * 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.UICmdtyCtgryListCond;
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.SIPrepared;
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 jp.co.sint.tools.SIUtil;

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

/**
 * @version $Id: SIRegCmdtyCtgrySrv.java,v 1.0 2003/09/22 Exp $
 * @author  Jinwang Chen
 * <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>
 * Jinwang Chen  2003/09/22 10:40:29  Original
 */
public class SIRegCmdtyCtgrySrv 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);//セッションの取得
    SIDatabaseConnection databaseConnection=new SIDatabaseConnection();//DBへのコネクションの作成
	SIURLParameter urlParam = new SIURLParameter(request);//7.1.1 ST0236 追加
    try {
	  String actionName=this.getActionName(urlParam);//画面からのアクション	//7.1.1 ST0236 修正
	  String editMode=this.getEditMode(urlParam);//DBへの編集モード	//7.1.1 ST0236 修正

      UICmdtyCtgryListCond cmdtyCtgryList=new UICmdtyCtgryListCond();//商品カテゴリの部分

      if (SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName)){//商品カテゴリ関連リスト
		cmdtyCtgryList.init(request,databaseConnection.getConnection(),urlParam);//7.1.1 ST0236 修正
        session.setAttribute(SIConfig.SISESSION_MAN_CMDTY_CTGRY_LIST_NAME,cmdtyCtgryList);
        //databaseConnection.close();
        forwardKey(request,response,"webshop.jsp.manager.cmdtyCtgry.list");
      }else if (SIConfig.SIACTION_DELETE.equalsIgnoreCase(actionName)){//レコードの削除
        //データの取得
        cmdtyCtgryList=new UICmdtyCtgryListCond();
		cmdtyCtgryList.init(request,urlParam);//7.1.1 ST0236 修正
        //データのチェック
        try {
          deleteTableData(databaseConnection.getConnection(),cmdtyCtgryList);
          request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                               SIErrorFactory.getErrorMsg("manager.message.success.delete"));
          try {databaseConnection.getConnection().commit();}catch(SQLException sqle){}
        } 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);
        }
        forwardKey(request,response,"webshop.jsp.manager.cmdtyCtgry.list");
      }else{//DBへのデータ登録
        //データの取得
        cmdtyCtgryList=new UICmdtyCtgryListCond();
        cmdtyCtgryList.init(request,urlParam);//7.1.1 ST0236 修正
        //データのチェック
        try {
          insertTableData(databaseConnection.getConnection(),cmdtyCtgryList);
          request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                               SIErrorFactory.getErrorMsg("manager.message.success.insert"));
          try {databaseConnection.getConnection().commit();}catch(SQLException sqle){sqle.printStackTrace();}
        } catch (SIDBAccessException sqle) {
          try {databaseConnection.getConnection().rollback();}catch(SQLException e){e.printStackTrace();}
          sqle.printStackTrace();
          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.cmdtyCtgry.list");
      }
    }catch (SQLException e){
      e.printStackTrace();
      throw new ServletException();
    }catch (NamingException e){
      e.printStackTrace();
      throw new ServletException();
    }finally{
      databaseConnection.close();
    }

  }

  /**
   * <b>insertTableData</b>
   * データベースに既存のレコードがあれば、削除します。同時に新規のレコードを作成します。
   * @param lConnection DBへのコネクション
   * @param cmdtyCtgryList 選択したカテゴリコード
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public void insertTableData(Connection lConnection ,UICmdtyCtgryListCond cmdtyCtgryList) throws SIDBAccessException{
    //新規のレコードの作成
    SIPrepared lPrepared=new  SIPrepared();
    String[] lCtgryCodeList=cmdtyCtgryList.getCtgryCodeChk();
    SIDeleteRec lRec=new SIDeleteRec("CmdtyCtgryMTbl");

    for (int ii=0;ii<lCtgryCodeList.length ;ii++){
      if (SIUtil.isNotNull(lCtgryCodeList[ii])){
        lRec=new SIDeleteRec("CmdtyCtgryMTbl");
        lRec.addCondition("ShopCode",cmdtyCtgryList.getShopCode());
        lRec.addCondition("CmdtyCode",cmdtyCtgryList.getCmdtyCode());
        lRec.addCondition("CtgryCode",lCtgryCodeList[ii]);
        try {lRec.execute(lConnection);}catch (SIDuplicateKeyException e) {e.printStackTrace();}

        lPrepared=new  SIPrepared("table.cmdtyCtgry.insert.sql");
        lPrepared.add(cmdtyCtgryList.getShopCode());
        lPrepared.add(cmdtyCtgryList.getCmdtyCode());
        lPrepared.add(lCtgryCodeList[ii]);
        log.debug("getShopCode="+cmdtyCtgryList.getShopCode()+",getCmdtyCode="+cmdtyCtgryList.getCmdtyCode()+",CtgryCodeList="+lCtgryCodeList[ii]);
        try {lPrepared.execute(lConnection);}catch(SIDuplicateKeyException sqle){}
      }
    }
  }

  /**
   * <b>deleteTableData</b>
   * 選択したカテゴリコードを商品カテゴリ関連テーブルから削除します。
   * @param lConnection DBへのコネクション
   * @param cmdtyCtgryList 選択したカテゴリコード
   * @return なし
   * @throws SIDBAccessException
   */
  public void deleteTableData(Connection lConnection ,UICmdtyCtgryListCond cmdtyCtgryList) throws SIDBAccessException{
    SIDeleteRec lRec=new SIDeleteRec("CmdtyCtgryMTbl");

    if (SIUtil.isNotNull(cmdtyCtgryList.getCtgryCode())){//選択したカテゴリコードがあれば、
      lRec.addCondition("ShopCode",cmdtyCtgryList.getShopCode());//ショップコード
      lRec.addCondition("CmdtyCode",cmdtyCtgryList.getCmdtyCode());//商品コード
      lRec.addCondition("CtgryCode",cmdtyCtgryList.getCtgryCode());//カテゴリコード
      try {
        lRec.execute(lConnection);
      } catch (SIDuplicateKeyException e) {
        throw new SIDBAccessException(e);
      }
    }
  }

  public void destroy() {
  }
}
