package jp.co.sint.servlet.mallmgr;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
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.UIBGRanking;
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.SIDeleteRec;
import jp.co.sint.database.SIDuplicateKeyException;
import jp.co.sint.database.SIInsertRec;
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 jp.co.sint.tools.SIURLParameter;

import org.apache.log4j.Category;

public class SIRegBGRankingSrv 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);// 7.1.1 ST0236 追加
    
    try {
      String actionName = this.getActionName(urlParam);// 画面からのアクション //7.1.1
      UIBGRanking bgRank = new UIBGRanking();
      
      if (SIConfig.SIACTION_REGIST.equalsIgnoreCase(actionName)) {
        bgRank.init(request, urlParam);
        if (!bgRank.validate(request, databaseConnection.getConnection())) {
          session.setAttribute(SIConfig.SISESSION_MAN_BGRANKING, bgRank);
          forwardKey(request, response, "webshop.jsp.manager.bgranking");
        } else {
          try {
            insertTableData(databaseConnection.getConnection(), bgRank);
            session.setAttribute(SIConfig.SISESSION_MAN_BGRANKING, bgRank);
            try {
              databaseConnection.getConnection().commit();
            } catch (SQLException sqle) {}
            request.setAttribute(SIConfig.SIMESSAGE_ATTRIBUTE_RESULT_NAME, SIErrorFactory.getErrorMsg("manager.message.success.insert"));
            session.setAttribute(SIConfig.SISESSION_MAN_BGRANKING, bgRank);
            forwardKey(request, response, "webshop.jsp.manager.bgranking");
          } catch (SIDBAccessException e) {
            try {
              databaseConnection.getConnection().rollback();
            } catch (SQLException ee) {}
            SICustomErrors errors = new SICustomErrors();
            errors.addError(new SICustomError("webshop.jsp.manager.bgranking"));
            request.setAttribute(SIConfig.SIERROR_ATTRIBUTE_MESSAGE_KEY, errors);
            session.setAttribute(SIConfig.SISESSION_MAN_BGRANKING, bgRank);
            forwardKey(request, response, "webshop.jsp.manager.bgranking");
          }
        }
      }
      
    } catch (SQLException e) {
      e.printStackTrace();
      throw new ServletException();
    } catch (NamingException e) {
      e.printStackTrace();
      throw new ServletException();
    } finally {
      databaseConnection.close();
    }
    
  }
  
  /**
   * <b>insertTableData</b> データベースにレコードを作成します。
   * 
   * @param lConnection DBへのコネクション
   * @param bgRank 入力したデータ
   * @return なし
   * @throws SIDuplicateKeyException
   * @throws SIDBAccessException
   */
  public static void insertTableData(Connection con, UIBGRanking bgRank) throws SIDBAccessException {
    try {
      SIDeleteRec delRec = new SIDeleteRec("bgrankingtbl");
      delRec.addCondition("shopcode", "0");
      delRec.execute(con);
      SIInsertRec inRec = new SIInsertRec("bgrankingtbl");
      
      String strCmdtyCode[] = new String[20];
      String strIndividualCode[] = new String[20];
      String strNumberOfSales[] = new String[20];
      String strComment[] = new String[20];
      int cnt = 0;
      StringTokenizer cmdtyToken = new StringTokenizer(bgRank.getCmdtyCode(), "\r\n");
      StringTokenizer individualToken = new StringTokenizer(bgRank.getIndividualCode(), "\r\n");
      StringTokenizer numberOfSalesToken = new StringTokenizer(bgRank.getNumberOfSales(), "\r\n");
      StringTokenizer commentToken = new StringTokenizer(bgRank.getComment(), "\r\n");
      while (cmdtyToken.hasMoreTokens()) {
        strCmdtyCode[cnt] = cmdtyToken.nextToken();
        cnt++;
      }
      cnt = 0;
      while (individualToken.hasMoreTokens()) {
        strIndividualCode[cnt] = individualToken.nextToken();
        cnt++;
      }
      cnt = 0;
      while (numberOfSalesToken.hasMoreTokens()) {
        strNumberOfSales[cnt] = numberOfSalesToken.nextToken();
        cnt++;
      }
      cnt = 0;
      while (commentToken.hasMoreTokens()) {
        strComment[cnt] = commentToken.nextToken();
        cnt++;
      }
      
      SISpcType lSpcType = new SISpcType();
      lSpcType = new SISpcType("TO_CHAR(now(),'YYYY/MM/DD HH24:MI:SS')::timestamp");
      
      inRec.add("shopcode", "0");
      inRec.add("rank", "0");
      inRec.add("comment", bgRank.getHeader());
      inRec.add("initdatetime", lSpcType);
      inRec.execute(con);
      
      for (int i = 0; i < 20; i++) {
        inRec = new SIInsertRec("bgrankingtbl");
        inRec.add("shopcode", "0");
        inRec.add("rank", i + 1);
        inRec.add("cmdtyCode", strCmdtyCode[i]);
        inRec.add("individualCode", strIndividualCode[i]);
        inRec.add("numberOfSales", strNumberOfSales[i]);
        inRec.add("comment", strComment[i]);
        inRec.add("initdatetime", lSpcType);
        inRec.execute(con);
      }
      
    } catch (SIDuplicateKeyException sqle) {
      throw new SIDBAccessException(sqle);
    }
    
  }
  
}
