/*  OpenOlap viewer
 *  パッケージ名：openolap.viewer.controller
 *  ファイル：SaveClientReportStatusCommand.java
 *  説明：
 *
 *  作成日: 2004/01/14
 */
package openolap.viewer.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;

import openolap.viewer.Report;
import openolap.viewer.common.CommonSettings;
import openolap.viewer.dao.AxisDAO;
import openolap.viewer.dao.ColorDAO;
import openolap.viewer.dao.DAOFactory;
import openolap.viewer.dao.ReportDAO;

/**
 *  クラス：SaveClientReportStatusCommand
 *  説明：
 */
public class SaveClientReportStatusCommand implements Command {

	private RequestHelper requestHelper = null;

	public String execute(RequestHelper helper, CommonSettings commonSettings)
		throws ServletException, IOException {

		String reportName = (String)helper.getRequest().getParameter("reportName");
		String folderID = (String)helper.getRequest().getParameter("folderID");

		// レポートを保存場所指定付きで保存
		if ( (!reportName.equals("")) && (!folderID.equals("")) ) {
			helper.getRequest().setAttribute("mode", "saveNewReport");
		}

		Connection conn = null;
		DAOFactory daoFactory = DAOFactory.getDAOFactory();
		conn = daoFactory.getConnection();

		// =========================================
		// Server側で保持しているレポートモデルを更新
		// =========================================

		// 色設定情報を更新
		ColorDAO colorDAO = daoFactory.getColorDAO(null);
		colorDAO.registColor(helper, commonSettings);

		// 軸のメンバのドリル状況
		AxisDAO axisDAO = daoFactory.getAxisDAO(null);
		axisDAO.registSelectedMemberAndDrillStat(helper, commonSettings);

		// レポート情報を更新
		ReportDAO reportDAO = daoFactory.getReportDAO(null);
		reportDAO.registReport(helper, commonSettings);

		// =========================================
		// レポート設定を永続化
		// =========================================
		Report report = (Report) helper.getRequest().getSession().getAttribute("report");
		try {
			conn.setAutoCommit(false);
			report.saveReport(conn);
			conn.commit();
		} catch (SQLException e) {
			try {
				if (conn != null){
					conn.rollback();
				}
				e.printStackTrace();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} catch (Exception e) {
			try {
				if (conn != null){
					conn.rollback();
				}
				e.printStackTrace();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
				}

			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}

		// =========================================
		// 終了処理
		// =========================================
		if(report.isNewReport()) {
			report.setNewReport(false);
		}

		return "/spread/saveFinalize.jsp";
	}

}
