/**
 * Copyright (c) 2003-2008 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 java.util.Collection;
import java.util.StringTokenizer;

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.UIFreeEstimateListCond;
import jp.co.sint.beans.mallmgr.UIRegUpdateEstimate;
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.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.SIURLParameter;

import org.apache.log4j.Category;

/**
 * @version $Id: SIFreeEstimateListSrv.java,v 1.0 2008/03/27 Exp $
 * @author Naotaka Ohsugi<br>
 * Description: 見積情報検索を行うServlet
 * <p>
 * History
 * </p>
 * Author          Date        Reason
 * ==============  ==========  =====================<br>
 * Naotaka Ohsugi  2008/03/27  Original
 */
public class SIFreeEstimateListSrv extends SIServlet {
  // ログ用のインスタンスの生成
  private static Category log = Category.getInstance(SIConfig.SILOG4J_WEBSHOP_CATEGORY_NAME);
  
  /**
   * <b>doUpdate</b> 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);
    
    String actionName = this.getActionName(urlParam); // 画面からのアクション
    try {
      Connection conn = databaseConnection.getConnection();
      
      if (actionName.equals(SIConfig.SIACTION_LIST)) {
        UIFreeEstimateListCond estimateList = new UIFreeEstimateListCond();
        estimateList.init(request, urlParam);
        estimateList.validate(request);
        session.setAttribute(SIConfig.SISESSION_MAN_ESTIMATE_FREEESTIMATE_LIST, estimateList);
        forwardKey(request, response, "webshop.jsp.manager.estimate.freeestimatelist");
      } else if (actionName.equals(SIConfig.SIACTION_DELETE)) {
        UIFreeEstimateListCond estimateList = new UIFreeEstimateListCond();
        estimateList.initDel(request, urlParam);
        if (estimateList.validateDelete(request)) {// 7.3.0 PI-NES0501
          if (estimateList.getEstimateCheck() != null) {
            String[] target = estimateList.getEstimateCheck();
            try {
              for (int i = 0; i < estimateList.getEstimateCheck().length; i++) {
                deleteEstimate(conn, target[i]);
              }
              try {conn.commit();} catch (SQLException sqle) {}
              request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.delete"));
              forwardKey(request, response, "webshop.jsp.manager.estimate.freeestimatelist");
            } catch (SIDBAccessException sqle) {
              try {conn.rollback();} catch (SQLException ee) {}
              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.estimate.freeestimatelist");
            }
          } else {
            forwardKey(request, response, "webshop.jsp.manager.estimate.freeestimatelist");
          }
        } else {
          forwardKey(request, response, "webshop.jsp.manager.estimate.freeestimatelist");
        }
      } else if (actionName.equals(SIConfig.SIACTION_DETAIL)) {
        UIFreeEstimateListCond estimateList = (UIFreeEstimateListCond) session.getAttribute(SIConfig.SISESSION_MAN_ESTIMATE_FREEESTIMATE_LIST);
        if (estimateList == null) estimateList = new UIFreeEstimateListCond();
        estimateList.init(request, urlParam);
        estimateList.validate(request);
        UIRegUpdateEstimate updateEstimate = new UIRegUpdateEstimate();
        try {
          updateEstimate.initializeFree(conn, estimateList.getEstimateCodeTxt(), manLogin);
          // EDBTG003-00 elecs-matsushima add start
          Collection setDataColl = updateEstimate.initializeFreeSet(conn, estimateList.getEstimateCodeTxt());
          session.setAttribute(SIConfig.SISESSION_MAN_ESTIMATE_FREEKEEP_SET_LIST, setDataColl);
          // EDBTG003-00 elecs-matsushima add end
        } catch (SIDBAccessException sqle) {
          sqle.printStackTrace();
        }
        session.setAttribute(SIConfig.SISESSION_MAN_ESTIMATE_FREEESTIMATE_UPDATE, updateEstimate);
        session.setAttribute(SIConfig.SISESSION_MAN_ESTIMATE_FREEESTIMATE_LIST, estimateList);
        forwardKey(request, response, "webshop.jsp.manager.estimate.freeestimateupdate");
      } else {
        forwardKey(request, response, "webshop.jsp.manager.estimate.freeestimatelist");
      }
    } catch (SQLException e) {
      e.printStackTrace();
      throw new ServletException();
    } catch (NamingException e) {
      e.printStackTrace();
      throw new ServletException();
    } finally {
      databaseConnection.close();
    }
  }
  
  public boolean deleteEstimate(Connection conn, String delTarget) throws SIDBAccessException {
    StringTokenizer delToken = new StringTokenizer(delTarget, "_");
    String estimateCode = delToken.nextToken();
    try {
      SIDeleteRec delRec = new SIDeleteRec("freeestimatetbl");
      delRec.addCondition("estimatecode", estimateCode);
      delRec.execute(conn);
      delRec = new SIDeleteRec("freeestimatedetailtbl");
      delRec.addCondition("estimatecode", estimateCode);
      delRec.execute(conn);
      delRec = new SIDeleteRec("freeestimatedeliverytbl");
      delRec.addCondition("estimatecode", estimateCode);
      delRec.execute(conn);
      return true;
    } catch (SIDuplicateKeyException e) {
      throw new SIDBAccessException(e);
    }
  }
  
  public void destroy() {}
}
