/**
 * 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.UIRegStndrdContent;
import jp.co.sint.beans.mallmgr.UIStndrdContentListCond;
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.SIHTMLUtil;

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

/**
 * @version $Id: SIRegStndrdContentSrv.java,v 1.0 2003/09/09 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/08  Original
 */

public class SIRegStndrdContentSrv 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 修正

      UIStndrdContentListCond stndrdContentListCond=new UIStndrdContentListCond();

      if (SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName)){//一覧と検索などの画面
        //データの取得
        stndrdContentListCond=new UIStndrdContentListCond();
		stndrdContentListCond.init(request,databaseConnection.getConnection(),urlParam);//7.1.1 ST0236 修正
        session.setAttribute(SIConfig.SISESSION_MAN_STNDRD_CONTENT_LIST_NAME,stndrdContentListCond);
        UIRegStndrdContent regStndrdContentID = new UIRegStndrdContent();
        session.setAttribute(SIConfig.SISESSION_MAN_STNDRD_CONTENT_EDIT_NAME,regStndrdContentID);
        forwardKey(request,response,"webshop.jsp.manager.stndrdContent.list");
      }else if (SIConfig.SIACTION_MODIFY.equalsIgnoreCase(actionName)){//レコードの修正
        //データの取得とデータのチェック
        session.removeAttribute(SIConfig.SISESSION_MAN_STNDRD_CONTENT_EDIT_NAME);
        UIRegStndrdContent regStndrdContent=new UIRegStndrdContent();
		regStndrdContent.initModify(request,urlParam);//7.1.1 ST0236 修正
        if (!regStndrdContent.validateUpdate(request)){//エラーがあれば
          session.setAttribute(SIConfig.SISESSION_MAN_STNDRD_CONTENT_EDIT_NAME,regStndrdContent);
          forwardKey(request,response,"webshop.jsp.manager.stndrdContent.list");
        }else{//エラーがなければ
          try {
            //データレコードの修正
            updateTableData(databaseConnection.getConnection(),regStndrdContent);
            request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                 SIErrorFactory.getErrorMsg("manager.message.success.modify"));
            try{databaseConnection.getConnection().commit();}catch(SQLException sqle){}
            forwardKey(request,response,"webshop.jsp.manager.stndrdContent.list");
          } catch (SIDBAccessException e) {
            try{databaseConnection.getConnection().rollback();}catch(SQLException sqle){}
            session.setAttribute(SIConfig.SISESSION_MAN_STNDRD_CONTENT_EDIT_NAME,regStndrdContent);
            SICustomErrors errors=new SICustomErrors();
            errors.addError(new SICustomError("database.execute.error"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK,errors);
            forwardKey(request,response,"webshop.jsp.manager.stndrdContent.list");
          }
        }
      }else if (SIConfig.SIACTION_NEW.equalsIgnoreCase(actionName)){//新規のレコード
        //データの取得とデータのチェック
        session.removeAttribute(SIConfig.SISESSION_MAN_STNDRD_CONTENT_EDIT_NAME);
        UIRegStndrdContent regStndrdContent=new UIRegStndrdContent();
		regStndrdContent.initInsert(request,urlParam);//7.1.1 ST0236 修正
        if (!regStndrdContent.validateInsert(request,databaseConnection.getConnection())){//エラーがあれば
          session.setAttribute(SIConfig.SISESSION_MAN_STNDRD_CONTENT_EDIT_NAME,regStndrdContent);
          forwardKey(request,response,"webshop.jsp.manager.stndrdContent.list");
        }else{//エラーがなければ
          try {
            //新規レコードの作成
            insertTableData(databaseConnection.getConnection(),regStndrdContent);
            request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                 SIErrorFactory.getErrorMsg("manager.message.success.insert"));
            try{databaseConnection.getConnection().commit();}catch(SQLException sqle){}
            forwardKey(request,response,"webshop.jsp.manager.stndrdContent.list");
          } catch (SIDuplicateKeyException e) {
            try{databaseConnection.getConnection().rollback();}catch(SQLException sqle){}
            session.setAttribute(SIConfig.SISESSION_MAN_STNDRD_CONTENT_EDIT_NAME,regStndrdContent);
            SICustomErrors errors=new SICustomErrors();
            errors.addError(new SICustomError("database.insert.duplicate2","規格コードが同一"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK,errors);
            forwardKey(request,response,"webshop.jsp.manager.stndrdContent.list");
          } catch (SIDBAccessException e) {
            try{databaseConnection.getConnection().rollback();}catch(SQLException sqle){}
            session.setAttribute(SIConfig.SISESSION_MAN_STNDRD_CONTENT_EDIT_NAME,regStndrdContent);
            SICustomErrors errors=new SICustomErrors();
            errors.addError(new SICustomError("database.execute.error"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK,errors);
            forwardKey(request,response,"webshop.jsp.manager.stndrdContent.list");
          }
        }
      }else if (SIConfig.SIACTION_DELETE.equalsIgnoreCase(actionName)){//レコードの削除
        //データの取得
        session.removeAttribute(SIConfig.SISESSION_MAN_STNDRD_CONTENT_EDIT_NAME);
        UIRegStndrdContent regStndrdContent=new UIRegStndrdContent();
		regStndrdContent.initModify(request,urlParam);//7.1.1 ST0236 修正
        try {
          if (!regStndrdContent.validateDelete(request,databaseConnection.getConnection())){//エラーがあれば
            forwardKey(request,response,"webshop.jsp.manager.stndrdContent.list");
          }else{//エラーがなければ
            //レコードの削除
            deleteTableData(databaseConnection.getConnection(),regStndrdContent);
            request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                 SIErrorFactory.getErrorMsg("manager.message.success.delete"));
            try{databaseConnection.getConnection().commit();}catch(SQLException sqle){}
            forwardKey(request,response,"webshop.jsp.manager.stndrdContent.list");
          }
        } catch (SIDBAccessException e) {
          try{databaseConnection.getConnection().rollback();}catch(SQLException sqle){}
          e.printStackTrace();
          SICustomErrors errors=new SICustomErrors();
          errors.addError(new SICustomError("database.execute.error"));
          request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY_BAK,errors);
          forwardKey(request,response,"webshop.jsp.manager.stndrdContent.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 regStndrdName 入力したデータ
	 * @return なし
	 * @throws SIDuplicateKeyException
	 * @throws SIDBAccessException
	 */
	public static void insertTableData(Connection lConnection,UIRegStndrdContent regStndrdContent) throws SIDuplicateKeyException,SIDBAccessException{
		SISpcType lSpcType=new SISpcType();

		SIInsertRec lRec=new SIInsertRec("StndrdContentMTbl");
		lRec.add("ShopCode",regStndrdContent.getShopCode());//ショップコード
		lRec.add("StndrdCode",regStndrdContent.getStndrdCode());//規格コード
		lRec.add("ElementCode",regStndrdContent.getElementCode());//エレメントコード
		lRec.add("ElementName",regStndrdContent.getElementName());//エレメント名称
		lRec.add("DispOrder",regStndrdContent.getDispOrder());//エレメント名称

		//実行
		lRec.execute(lConnection);
	}

	/**
	 * <b>updateTableData</b>
	 * データベースにレコードを修正します。
	 * @param lConnection DBへのコネクション
	 * @param regStndrdContent 入力したデータ
	 * @return なし
	 * @throws SIDuplicateKeyException
	 * @throws SIDBAccessException
	 */
	public static void updateTableData(Connection lConnection,UIRegStndrdContent regStndrdContent)throws SIDBAccessException {
		SIModifyRec lRec=new SIModifyRec("StndrdContentMTbl");

		lRec.addCondition("ShopCode",regStndrdContent.getShopCode());//ショップコード
		lRec.addCondition("StndrdCode",regStndrdContent.getStndrdCode());//規格コード
		lRec.addCondition("ElementCode",regStndrdContent.getRegElementCodeTxt());//エレメントコード
		lRec.add("ElementName",regStndrdContent.getRegElementNameTxt());//規格名称
		lRec.add("DispOrder",regStndrdContent.getRegDispOrderTxt());//表示順序

		try {
			lRec.execute(lConnection);
		} catch (SIDuplicateKeyException e) {
			throw new SIDBAccessException("modify data error.");
    }
	}

	/**
	 * <b>deleteTableData</b>
	 * データベースにレコードを削除します。
	 * @param lConnection DBへのコネクション
	 * @param regStndrdContent 削除するデータ
	 * @return なし
	 * @throws SIDuplicateKeyException
	 * @throws SIDBAccessException
	 */
	private void deleteTableData(Connection lConnection,UIRegStndrdContent regStndrdContent) throws SIDBAccessException{

		SIDeleteRec lRec=new SIDeleteRec("StndrdContentMTbl");

		lRec.addCondition("ShopCode",regStndrdContent.getShopCode());//ショップコード
		lRec.addCondition("StndrdCode",regStndrdContent.getStndrdCode());//規格コード
		lRec.addCondition("ElementCode",regStndrdContent.getRegElementCodeTxt());//エレメントコード

		try {
			lRec.execute(lConnection);
		} catch (SIDuplicateKeyException e) {
			throw new SIDBAccessException("delete data error.");
		}
	}

	public void destroy() {
	}
}
