/**
 * Created on 2003/10/02
 *
 * 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.io.PrintWriter;
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.UIRegInstockList;
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.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 追加

/**
 * @author arai
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class SIRegInstockSrv extends SIServlet {
  //ログ用のインスタンスの生成
  private static Category log = Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);

  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);//セッションの取得
    
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();

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

    UIRegInstockList regList = new UIRegInstockList();
    SIDatabaseConnection databaseConnection = new SIDatabaseConnection();

    try {
      Connection connection=databaseConnection.getConnection();;

      if (SIConfig.SIACTION_NEW.equalsIgnoreCase(actionName)) {
        //一覧と検索などの画面
        regList.setActionNameTxt(SIConfig.SIACTION_NEW);
        session.setAttribute(SIConfig.SISESSION_MAN_INSTOCK_LIST_NAME, regList);
        forwardKey(request, response, "webshop.jsp.manager.instock.list");
      } else if (SIConfig.SIACTION_REMODIFY.equalsIgnoreCase(actionName)) {
        //一覧と検索などの画面
		regList.init(urlParam);//7.1.1 ST0236 修正
        session.setAttribute(SIConfig.SISESSION_MAN_INSTOCK_LIST_NAME, regList);
        forwardKey(request, response, "webshop.jsp.manager.instock.list");
      } else {
		regList.init(urlParam);//7.1.1 ST0236 修正
        //データのチェック
		if (regList.validate(request, connection,urlParam) == false) {//7.1.1 ST0236 修正
          request.setAttribute("remodify", SIConfig.SIACTION_REMODIFY);
          regList.setActionNameTxt(SIConfig.SIACTION_REMODIFY);
          session.setAttribute(SIConfig.SISESSION_MAN_INSTOCK_LIST_NAME, regList);
          forwardKey(request, response, "webshop.jsp.manager.instock.edit");
        } else {
          regList.setActionNameTxt(SIConfig.SIACTION_NEW);
          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)){
              if(regList.validateData(connection)) {
                  SICustomErrors errors = new SICustomErrors();
                                  errors.addError(new SICustomError("database.delete.lock2"));
                                  request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
              }else{
                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.instock.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.instock.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.instock.edit");
          }
        }
      }
    }catch (SQLException e){
      e.printStackTrace();
      throw new ServletException();
    }catch (NamingException e){
      e.printStackTrace();
      throw new ServletException();
    }finally{
      databaseConnection.close();
    }

  }

  /**
  * insertTableData
  * データベースにレコードを修正します。
  * @param
  * @return
  * @throws
  */
  private void insertTableData(UIRegInstockList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
    SISpcType lSpcType = new SISpcType();
    SIInsertRec lRec = new SIInsertRec("stockstatusmtbl");

    lRec.add("StockStatusName", regList.getStockStatusName());
    lRec.add("CommentOfNoStock", regList.getCommentOfNoStock());
    lRec.add("AmountOfLessStock", regList.getAmountOfLessStock());
    lRec.add("CommentOfLessStock", regList.getCommentOfLessStock());
    lRec.add("CommentOfMoreStock", regList.getCommentOfMoreStock());

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

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

  /**
  * updateTableData
  * データベースにレコードを修正します。
  * @param
  * @return
  * @throws
  */
  private void updateTableData(UIRegInstockList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
    SISpcType lSpcType = new SISpcType();
    SIModifyRec lRec = new SIModifyRec("stockstatusmtbl");

    lRec.addCondition("stockstatuscode", regList.getStockStatusCode());

    lRec.add("StockStatusName", regList.getStockStatusName());
    lRec.add("CommentOfNoStock", regList.getCommentOfNoStock());
    lRec.add("AmountOfLessStock", regList.getAmountOfLessStock());
    lRec.add("CommentOfLessStock", regList.getCommentOfLessStock());
    lRec.add("CommentOfMoreStock", regList.getCommentOfMoreStock());

    log.debug("update sql=" + lRec.getSQL());

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

  /**
  	* deleteTableData
  	* データベースにレコードを修正します。
  	* @param
  	* @return
  	* @throws
  	*/
  private void deleteTableData(UIRegInstockList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
	SIDeleteRec lDeleteRec = new SIDeleteRec();
	StringBuffer lSqlBuf=new StringBuffer();

	lSqlBuf.append("DELETE FROM stockstatusMtbl ");
	lSqlBuf.append("WHERE stockstatuscode =(SELECT a.stockstatuscode  FROM stockstatusMtbl a");
	lSqlBuf.append("  LEFT OUTER JOIN  ");
	lSqlBuf.append("   (SELECT stockstatuscode,COUNT(cmdtycode) as cmdtyCount ");
	lSqlBuf.append("    FROM cmdtyMtbl GROUP BY stockstatuscode ) b");
	lSqlBuf.append("  ON (a.stockstatuscode = b.stockstatuscode)  ");
	lSqlBuf.append("  WHERE cmdtyCount IS NULL and a.stockstatuscode=").append(SIDBUtil.SQL2Str(regList.getStockStatusCode())).append(")");	

	lDeleteRec.setSQL(lSqlBuf.toString());

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

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

  public void destroy() {
  }
}
