/**
 * Created on 2003/08/26
 *
 * 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.UINewsList;
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.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 SIRegNewsSrv 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);//セッションの取得
    SIDatabaseConnection databaseConnection = new SIDatabaseConnection();//DBへのコネクションの作成
    SIURLParameter urlParam = new SIURLParameter(request);
    try {
      String actionName=this.getActionName(urlParam);//画面からのアクション
      String editMode = this.getEditMode(urlParam);//DBへの編集モード
      
      UINewsList regList = new UINewsList();
      
      //データベースへのコネクションの作成
      Connection connection = databaseConnection.getConnection();
      
      if (SIConfig.SIACTION_LIST.equalsIgnoreCase(actionName)) { //一覧と検索などの画面
        //データの取得とデータのチェック
        regList.init(urlParam);
        session.setAttribute(SIConfig.SISESSION_MAN_NEWS_LIST_NAME, regList);
        forwardKey(request, response, "webshop.jsp.manager.news.list");
      } else if (SIConfig.SIACTION_PREVIEW.equalsIgnoreCase(actionName)) { //プレビュー
        //データの取得とデータのチェック
        regList.init(urlParam);
        session.setAttribute(SIConfig.SISESSION_MAN_NEWS_LIST_NAME, regList);
        forwardKey(request, response, "webshop.jsp.manager.news.preview");
      } else {
        //データの取得
        regList.init(urlParam);
        //データのチェック
        if (regList.validate(request, connection) == false) {
          session.setAttribute(SIConfig.SISESSION_MAN_NEWS_LIST_NAME, regList);
          request.setAttribute("remodify", SIConfig.SIACTION_REMODIFY);
          forwardKey(request, response, "webshop.jsp.manager.news.list");
        } else {
          regList.setActionNameTxt(SIConfig.SIACTION_LIST);
          session.setAttribute(SIConfig.SISESSION_MAN_NEWS_LIST_NAME, regList);
          regList = (UINewsList) session.getAttribute(SIConfig.SISESSION_MAN_NEWS_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.news.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.news.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.news.edit");
          }
        }
      }
    }catch (SQLException e){
      e.printStackTrace();
      throw new ServletException();
    }catch (NamingException e){
      e.printStackTrace();
      throw new ServletException();
    }finally{
      databaseConnection.close();
    }
  }
  
  /**
   * insertTableData
   * データベースにレコードを作成します。
   * @param
   * @return
   * @throws
   */
  public void insertTableData(UINewsList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
    SIInsertRec lRec = new SIInsertRec("newsmtbl");
    SIDateTime lDate = new SIDateTime();
    
    lRec.add("startdatetime", regList.getStartDateTime());
    lRec.add("initdatetime", lDate.getFullDateTime());
    lRec.add("updatedatetime", lDate.getFullDateTime());
    lRec.add("description", regList.getDescription());
    lRec.add("dispflg", regList.getDispFlag());
    
    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(UINewsList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
    SIModifyRec lRec = new SIModifyRec("newsmtbl");
    SIDateTime lDate = new SIDateTime();
    
    lRec.addCondition("newscode", Integer.parseInt(regList.getNewsCode()));
    
    lRec.add("startdatetime", regList.getStartDateTime());
    lRec.add("updatedatetime", lDate.getFullDateTime());
    lRec.add("description", regList.getDescription());
    lRec.add("delflag", regList.getDelFlag());
    lRec.add("dispflg", regList.getDispFlag());
    
    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
   */
  public void deleteTableData(UINewsList regList, Connection connection) throws SIDuplicateKeyException, SIDBAccessException {
    SIDeleteRec lDeleteRec = new SIDeleteRec();
    
    if (regList.getNewsCode() != "") {
      lDeleteRec = new SIDeleteRec();
      lDeleteRec.setTableName("newsmtbl");
      lDeleteRec.addCondition("newscode", regList.getNewsCode());
      
      //データの更新
      log.debug("delete sql=" + lDeleteRec.getSQL());
      lDeleteRec.execute(connection);
    }
    try {
      connection.commit();
    } catch (SQLException sqle) {
      throw new SIDBAccessException("delete data error.");
    }
  }
  
  public void destroy() {}
}
