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.UIRegStorage;
import jp.co.sint.beans.mallmgr.UIStorageListCond;
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.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;

/**
 * @version $Id: SIRegStorageSrv.java,v 1.0 2016/1/27 Exp $
 * @author  Naotaka Ohsugi
 * <br>Description:
 * <p>History</p>
 * <p>Author/Date/Reason</p>
 *  =================<br>
 *   Ohsugi  2016/1/27  Original
 */
public class SIRegStorageSrv 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);
    try {
      Connection connection;
      
      String actionName = this.getActionName(urlParam);//画面からのアクション
      String editMode = this.getEditMode(urlParam); //DBへの編集モード
      
      UIStorageListCond regList = new UIStorageListCond();
      UIRegStorage regStorage = new UIRegStorage();
      
      //データベースへのコネクションの作成
      connection = databaseConnection.getConnection();
      
      if (SIConfig.SIACTION_NEW.equalsIgnoreCase(actionName)) {
        forwardKey(request, response, "webshop.jsp.manager.storage.edit");
      } else if (SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName) || (SIUtil.isNull(actionName) & SIUtil.isNull(editMode))) {
        regList.init(request,urlParam);
        regList.validate(request);
        session.setAttribute(SIConfig.SISESSION_MAN_STORAGE_LIST_NAME, regList);
        forwardKey(request, response, "webshop.jsp.manager.storage.list");
      } else if (SIConfig.SIACTION_DETAIL.equalsIgnoreCase(actionName)) {
        regList.init(request,urlParam);
        regStorage = new UIRegStorage(regList.getStorageCode());
        regStorage.reset(connection);
        regStorage.setEditModeTxt(SIConfig.SIEDIT_MODE_UPDATE);
        session.setAttribute(SIConfig.SISESSION_MAN_STORAGE_EDIT_NAME, regStorage);
        forwardKey(request, response, "webshop.jsp.manager.storage.edit");
      } else if (SIConfig.SIACTION_NEW.equalsIgnoreCase(actionName)) {
        regStorage = new UIRegStorage();
        regStorage.setEditModeTxt(SIConfig.SIEDIT_MODE_INSERT);
        session.setAttribute(SIConfig.SISESSION_MAN_STORAGE_EDIT_NAME, regStorage);
        forwardKey(request, response, "webshop.jsp.manager.storage.edit");
      } else if (SIConfig.SIACTION_REFRESH.equalsIgnoreCase(actionName)) {
        if (editMode.equals(SIConfig.SIEDIT_MODE_UPDATE)){
          regStorage = new UIRegStorage((String) urlParam.getParam("storageCode"));
          regStorage.reset(connection);
        } else if (editMode.equals(SIConfig.SIEDIT_MODE_INSERT)) {
          regStorage = new UIRegStorage();
        }
        regStorage.setEditModeTxt(editMode);
        session.setAttribute(SIConfig.SISESSION_MAN_STORAGE_EDIT_NAME, regStorage);
        forwardKey(request, response, "webshop.jsp.manager.storage.edit");
      } else if (SIConfig.SIACTION_BACK.equalsIgnoreCase(actionName)) {//確認画面から明細画面に戻る
        forwardKey(request, response, "webshop.jsp.manager.storage.edit");
      } else if (SIConfig.SIACTION_RETURN.equalsIgnoreCase(actionName)) {//明細画面、完了画面から一覧画面へ戻る
        forwardKey(request, response, "webshop.jsp.manager.storage.list");
      } else if (SIConfig.SIACTION_DELETE.equals(actionName)){
        regList.init(request,urlParam);
        try {
          deleteTableData(regList.getStorageCode(), connection);
          request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,SIErrorFactory.getErrorMsg("manager.message.success.delete"));
          try {connection.commit();} catch (SQLException sqle) {}
        } 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, regStorage, editMode);
          forwardKey(request, response, "webshop.jsp.manager.storage.list");
        } 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.storage.list");
        }
        forwardKey(request, response, "webshop.jsp.manager.storage.list");
      } else if (SIConfig.SIACTION_CONFIRM.equals(actionName)){
        regStorage.init(request, urlParam);
        session.setAttribute(SIConfig.SISESSION_MAN_STORAGE_EDIT_NAME, regStorage);
        if (regStorage.validate(request,connection)) {
          forwardKey(request, response, "webshop.jsp.manager.storage.confirm");
        } else {
          forwardKey(request, response, "webshop.jsp.manager.storage.edit");
        }
      } else if (SIConfig.SIACTION_REGIST.equals(actionName)){
        regStorage = (UIRegStorage)session.getAttribute(SIConfig.SISESSION_MAN_STORAGE_EDIT_NAME);
        try {
          if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_INSERT)) {
            insertTableData(regStorage, connection);
            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(regStorage, connection);
            request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,SIErrorFactory.getErrorMsg("manager.message.success.modify"));
            try {connection.commit();} catch (SQLException sqle) {}
          } else log.error("no known edit mode.editMode=" + editMode);
          forwardKey(request, response, "webshop.jsp.manager.storage.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, regStorage, editMode);
          forwardKey(request, response, "webshop.jsp.manager.storage.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.storage.edit");
        }
      } else if (SIConfig.SIACTION_UPDATE.equals(actionName)){
        regStorage.init(request, urlParam);
        session.setAttribute(SIConfig.SISESSION_MAN_STORAGE_EDIT_NAME, regStorage);
        try {
          updateTableData2(regStorage, connection);
          request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME,SIErrorFactory.getErrorMsg("manager.message.success.modify"));
          try {connection.commit();} catch (SQLException sqle) {}
          forwardKey(request, response, "webshop.jsp.manager.storage.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, regStorage, editMode);
          forwardKey(request, response, "webshop.jsp.manager.storage.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.storage.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, UIRegStorage regStorage, String editMode) {
    HttpSession session=request.getSession(true);//セッションの取得
    
    if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_INSERT)) {
      regStorage.setActionNameTxt(SIConfig.SIACTION_NEW);
    } else if (editMode.equalsIgnoreCase(SIConfig.SIEDIT_MODE_UPDATE)) {
      regStorage.setActionNameTxt(SIConfig.SIACTION_LIST);
    }
    session.setAttribute(SIConfig.SISESSION_MAN_STORAGE_LIST_NAME, regStorage);
    request.setAttribute("remodify", SIConfig.SIACTION_REMODIFY);
  }
  
  /**
  * insertTableData
  * コードを作成します。
  * @param UIStockList
  * @param Connection
  * @return なし
  * @throws SIDuplicateKeyException
  * @throws SIDBAccessException
  */
  public void insertTableData(UIRegStorage regStorage, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
    SIInsertRec lRec = new SIInsertRec("StorageTbl");
    
    lRec.add("StorageCode", regStorage.getStorageCode());
    lRec.add("StorageName", regStorage.getStorageName());
    lRec.add("Email", regStorage.getEmail());
    lRec.add("Comment", regStorage.getComment());
    
    log.debug("insert sql=" + lRec.getSQL());
    lRec.execute(connection);
  }
  
  /**
  * updateTableData
  * レコードを修正します。
  * @param UIStockList
  * @param Connection
  * @return なし
  * @throws SIDuplicateKeyException
  * @throws SIDBAccessException
  */
  private void updateTableData(UIRegStorage regStorage, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
    SIModifyRec lRec = new SIModifyRec("StorageTbl");
    
    lRec.addCondition("StorageCode", regStorage.getStorageCode());
    lRec.add("StorageName", regStorage.getStorageName());
    lRec.add("Email", regStorage.getEmail());
    lRec.add("Comment", regStorage.getComment());
    
    log.debug("update sql=" + lRec.getSQL());
    lRec.execute(connection);
  }
  
  private void updateTableData2(UIRegStorage regStorage, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
    SIModifyRec lRec = new SIModifyRec("StorageTbl");
    
    lRec.addCondition("StorageCode", regStorage.getStorageCode());
    lRec.add("Comment", regStorage.getComment());
    
    log.debug("update sql=" + lRec.getSQL());
    lRec.execute(connection);
  }
  
  /**
  * deleteTableData
  * レコードを削除します。
  * @param UIStockList
  * @param Connection
  * @return なし
  * @throws SIDuplicateKeyException
  * @throws SIDBAccessException
  */
  public void deleteTableData(String lStorageCode, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
    SIDeleteRec lDeleteRec = new SIDeleteRec("StorageTbl");
    
    lDeleteRec.addCondition("StorageCode", lStorageCode);
    
    log.debug("delete sql=" + lDeleteRec.getSQL());
    lDeleteRec.execute(connection);
  }
  
  public void destroy() {
  }
}
