/**
 * Created on 2003/08/14
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
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.UIOpaqueList;
import jp.co.sint.config.SIConfig;
import jp.co.sint.config.SIDBMultiConf;
import jp.co.sint.database.SIDBAccessException;
import jp.co.sint.database.SIDatabaseConnection;
import jp.co.sint.database.SIDateTimeType;
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.SIDateTime;
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 追加

/**
 * @author arai
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */

public class SIRegOpaqueSrv extends SIServlet {

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

  /**
   * doUpdate
   * HTTP リクエストの処理
   * @param  なし
   * @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 {
      Connection connection;

      UIOpaqueList regList = new UIOpaqueList();

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

      //データベースへのコネクションの作成
      connection = databaseConnection.getConnection();

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

        //データのチェック
        if (regList.validate(request, connection) == false) {
          request.setAttribute("remodify",SIConfig.SIACTION_REMODIFY);
          forwardKey(request, response, "webshop.jsp.manager.opaque.edit");
        } else {
          regList = (UIOpaqueList) session.getAttribute(SIConfig.SISESSION_MAN_OPAQUE_LIST_NAME);
          try {
            if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_INSERT)){
              insertTableData(regList, connection);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.insert"));
            }else if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_UPDATE)){
              updateTableData(regList, connection);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.modify"));
            }else if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_DELETE)){
              deleteTableData(regList, connection);
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,
                                   SIErrorFactory.getErrorMsg("manager.message.success.delete"));
            }else log.error("no known edit mode.editMode=" + editMode);
            forwardKey(request, response, "webshop.jsp.manager.opaque.result");
          } catch (SIDuplicateKeyException sqle) {
            SICustomErrors errors = new SICustomErrors();
            errors.addError(new SICustomError("database.insert.duplicate"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
            forwardKey(request, response, "webshop.jsp.manager.opaque.edit");
          } catch (SIDBAccessException sqle) {
            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.opaque.edit");
          }
        }
      }
    }catch (SQLException e){
      e.printStackTrace();
      throw new ServletException();
    }catch (NamingException e){
      e.printStackTrace();
      throw new ServletException();
    }finally{
      databaseConnection.close();
    }
  }

  /**
   * insertTableData
   * レコードを挿入します。
   * @param UIOpaqueList , Connection
   * @return
   * @throws SIDuplicateKeyException, SIDBAccessException
   */
  public void insertTableData(UIOpaqueList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
    SISpcType lSpcType = new SISpcType();
    SIInsertRec lRec = new SIInsertRec("opaquemtbl");
    String now = (new SIDateTime()).getFullDateTime();

    lRec.add("disporder", regList.getDispOrder());
    lRec.add("description", regList.getDescription());
    if (SIDBMultiConf.SIDB_CURRENT_INX ==SIDBMultiConf.SIDB_POSTGRESQL_INX){
      lRec.add("startdatetime", regList.getStartDateTime());
      lRec.add("enddatetime", regList.getEndDateTime());
      lRec.add("initdatetime", now);
      lRec.add("updatedatetime", now);
    }else{
      lRec.add("startdatetime",new SIDateTimeType(regList.getStartDateTime()));
      lRec.add("enddatetime",new SIDateTimeType(regList.getEndDateTime()));
      lRec.add("initdatetime",new SIDateTimeType(now));
      lRec.add("updatedatetime",new SIDateTimeType(now));
    }

    log.debug("insert sql=" + lRec.getSQL());
    lRec.execute(connection);

    try {
      connection.commit();
    } catch (SQLException sqle) {
      throw new SIDBAccessException("insert data error.");
    }
  }

  /**
   * updateTableData
   * レコードを修正します。
   * @param UIOpaqueList , Connection
   * @return
   * @throws SIDuplicateKeyException, SIDBAccessException
   */
  private void updateTableData(UIOpaqueList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {

    SISpcType lSpcType = new SISpcType();
    String now = (new SIDateTime()).getFullDateTime();
    SIModifyRec lRec = new SIModifyRec("opaquemtbl");

    lRec.addCondition("opaquecode", Integer.parseInt(regList.getOpaqueCode()));
    lRec.add("disporder", regList.getDispOrder());
    lRec.add("description", regList.getDescription());
    if (SIDBMultiConf.SIDB_CURRENT_INX ==SIDBMultiConf.SIDB_POSTGRESQL_INX){
      lRec.add("startdatetime", regList.getStartDateTime());
      lRec.add("enddatetime", regList.getEndDateTime());
      lRec.add("updatedatetime",now);
    }else{
      lRec.add("startdatetime",new SIDateTimeType(regList.getStartDateTime()));
      lRec.add("enddatetime",new SIDateTimeType(regList.getEndDateTime()));
      lRec.add("updatedatetime",new SIDateTimeType(now));
    }

    log.debug("update sql=" + lRec.getSQL());
    lRec.execute(connection);
    try {
      connection.commit();
    } catch (SQLException sqle) {
      throw new SIDBAccessException("update data error.");

    }
  }

  /**
   * deleteTableData
   * レコードを削除します。
   * @param UIOpaqueList , Connection
   * @return
   * @throws SIDuplicateKeyException, SIDBAccessException
   */
  public void deleteTableData(UIOpaqueList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {

    SIDeleteRec lDeleteRec = new SIDeleteRec();

    if (regList.getOpaqueCode() != "") {
      lDeleteRec = new SIDeleteRec();
      lDeleteRec.setTableName("opaquemtbl");
      lDeleteRec.addCondition("opaquecode", Integer.parseInt(regList.getOpaqueCode()));
      //データの更新
      lDeleteRec.execute(connection);
    }
    try {
      connection.commit();
    } catch (SQLException sqle) {
      throw new SIDBAccessException("delete data error.");
    }
  }

  public void destroy() {
  }
}
