/*
 
Copyright (C) 2008 NTT DATA INTELLILINK CORPORATION
 
This program is free software; you can redistribute it and/or
Modify it under the terms of the GNU General Public License 
as published by the Free Software Foundation, version 2.
 
This program is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied 
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
PURPOSE.  See the GNU General Public License for more details.
 
*/

package jp.co.intellilink.hinemos.export.conf.calendar;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;

import jp.co.intellilink.hinemos.export.util.Config;
import jp.co.intellilink.hinemos.export.util.DateListComparator;
import jp.co.intellilink.hinemos.export.util.DayOfWeekListComparator;
import jp.co.intellilink.hinemos.export.util.EjbConnectionManager;
import jp.co.intellilink.hinemos.export.util.Messages;
import jp.co.intellilink.hinemos.export.util.StringListComparator;
import jp.co.intellilink.hinemos.export.util.WriteCsvFile;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.clustercontrol.bean.DayOfWeekConstant;
import com.clustercontrol.bean.YesNoConstant;
import com.clustercontrol.calendar.bean.AddListTableDefine;
import com.clustercontrol.calendar.bean.CalendarListTableDefine;
import com.clustercontrol.calendar.bean.WeekdayListTableDefine;
import com.clustercontrol.calendar.ejb.session.CalendarController;

/**
 * カレンダ情報を取得するクラス<br>
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
public class ExportCalendar {

	// ログ出力
	private static Log log = LogFactory.getLog(ExportCalendar.class);

	/**
	 * カレンダ情報をExportする。<br>
	 */
	public void exportCalendar() {
		log.info(Messages.getMsg("ExportTool.Calendar.Start"));

    	//CSV出力配列を用意
    	ArrayList<ArrayList<String>> csvCalendarOutput = new ArrayList<ArrayList<String>>();
    	ArrayList<ArrayList<String>> csvRuleOutput = new ArrayList<ArrayList<String>>();
    	ArrayList<ArrayList<String>> csvExceptionOutput = new ArrayList<ArrayList<String>>();
    	
		//カレンダ一覧取得
    	ArrayList list = getCalendarList();
    	if(list instanceof ArrayList){
			Iterator itr = list.iterator();
			while(itr.hasNext()){
				ArrayList line = (ArrayList)itr.next();
				
				String calendarId = (String)line.get(CalendarListTableDefine.CALENDAR_ID);
				Object[] args = {calendarId};
				log.info(Messages.getMsg("ExportTool.CalendarID", args));
				
				//カレンダ情報のCSV文字列作成
				csvCalendarOutput.add(createCalendarCsvFormat(line));
				
				//カレンダ実行規則情報のCSV文字列作成
				ArrayList ruleList = getRuleList(calendarId);
				Iterator itr2 = ruleList.iterator();
				while(itr2.hasNext()){
					ArrayList weekday = (ArrayList)itr2.next();
					ArrayList<String> output = createRuleCsvFormat(weekday);
					output.add(0, calendarId);
					csvRuleOutput.add(output);
				}
				
				//カレンダ実行例外情報のCSV文字列作成
				ArrayList exceptionList = getExceptionList(calendarId);
				Iterator itr3 = exceptionList.iterator();
				while(itr3.hasNext()){
					ArrayList add = (ArrayList)itr3.next();
					ArrayList<String> output = createExceptionCsvFormat(add);
					output.add(0, calendarId);
					csvExceptionOutput.add(output);
				}
			}
			
			//カレンダIDでソート
			Collections.sort(csvCalendarOutput, new StringListComparator(0));
			//曜日でソート
			Collections.sort(csvRuleOutput, new DayOfWeekListComparator(1));
			//カレンダIDでソート
			Collections.sort(csvRuleOutput, new StringListComparator(0));
			//日時(開始)でソート
			Collections.sort(csvExceptionOutput, new DateListComparator(1));
			//カレンダIDでソート
			Collections.sort(csvExceptionOutput, new StringListComparator(0));
    	}

		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
		WriteCsvFile.writeCsvFile(
				Config.getConfig("Output.Dir.Conf") + "/CALENDAR_" + format.format(new Date()) + ".csv", 
				csvCalendarOutput);
		WriteCsvFile.writeCsvFile(
				Config.getConfig("Output.Dir.Conf") + "/CALENDAR_RULE_" + format.format(new Date()) + ".csv", 
				csvRuleOutput);
		WriteCsvFile.writeCsvFile(
				Config.getConfig("Output.Dir.Conf") + "/CALENDAR_EXCEPTION_" + format.format(new Date()) + ".csv", 
				csvExceptionOutput);
		
		log.info(Messages.getMsg("ExportTool.Calendar.End"));
	}
	
	/**
	 * カレンダ情報のCSV文字列を作成する。<br>
	 * 
	 * @param info カレンダ情報
	 * @return CSVフォーマット文字列
	 */
	protected ArrayList<String> createCalendarCsvFormat(ArrayList info) {
		ArrayList<String> csvFormat = new ArrayList<String>();
		
		//カレンダID
		if(info.get(CalendarListTableDefine.CALENDAR_ID) instanceof String)
			csvFormat.add((String)info.get(CalendarListTableDefine.CALENDAR_ID));
		else
			csvFormat.add("");
		//カレンダ名
		if(info.get(CalendarListTableDefine.CALENDAR_NAME) instanceof String)
			csvFormat.add((String)info.get(CalendarListTableDefine.CALENDAR_NAME));
		else
			csvFormat.add("");
		//有効期間(開始)
		if(info.get(CalendarListTableDefine.VALID_TIME_FROM) instanceof Date)
			csvFormat.add(DateFormat.getDateTimeInstance().format((Date)info.get(CalendarListTableDefine.VALID_TIME_FROM)));
		else
			csvFormat.add("");
		//有効期間(終了)
		if(info.get(CalendarListTableDefine.VALID_TIME_TO) instanceof Date)
			csvFormat.add(DateFormat.getDateTimeInstance().format((Date)info.get(CalendarListTableDefine.VALID_TIME_TO)));
		else
			csvFormat.add("");
		//説明
		if(info.get(CalendarListTableDefine.DESCRIPTION) instanceof String)
			csvFormat.add((String)info.get(CalendarListTableDefine.DESCRIPTION));
		else
			csvFormat.add("");
		
		return csvFormat;
	}
	
	/**
	 * カレンダ実行規則情報のCSV文字列を作成する。<br>
	 * 
	 * @param info カレンダ実行規則情報
	 * @return CSVフォーマット文字列
	 */
	protected ArrayList<String> createRuleCsvFormat(ArrayList info) {
		ArrayList<String> csvFormat = new ArrayList<String>();
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        
		//曜日
		if(info.get(WeekdayListTableDefine.WEEKDAY) instanceof Integer)
			csvFormat.add(DayOfWeekConstant.typeToString((Integer)info.get(WeekdayListTableDefine.WEEKDAY)));
		else
			csvFormat.add("");
		//時刻(開始)
		if(info.get(WeekdayListTableDefine.TIME_FROM) instanceof Date)
			csvFormat.add(formatter.format((Date)info.get(WeekdayListTableDefine.TIME_FROM)));
		else
			csvFormat.add("");
		//時刻(終了)
		if(info.get(WeekdayListTableDefine.TIME_TO) instanceof Date)
			csvFormat.add(formatter.format((Date)info.get(WeekdayListTableDefine.TIME_TO)));
		else
			csvFormat.add("");
		//説明
		if(info.get(WeekdayListTableDefine.DESCRIPTION) instanceof String)
			csvFormat.add((String)info.get(WeekdayListTableDefine.DESCRIPTION));
		else
			csvFormat.add("");
		
		return csvFormat;
	}
	
	/**
	 * カレンダ実行例外情報のCSV文字列を作成する。<br>
	 * 
	 * @param info カレンダ実行例外情報
	 * @return CSVフォーマット文字列
	 */
	protected ArrayList<String> createExceptionCsvFormat(ArrayList info) {
		ArrayList<String> csvFormat = new ArrayList<String>();
        
		//実行
		if(info.get(AddListTableDefine.EXECUTE) instanceof Boolean){
			Boolean execute = (Boolean)info.get(AddListTableDefine.EXECUTE);
			if(execute)
				csvFormat.add(YesNoConstant.STRING_YES);
			else
				csvFormat.add(YesNoConstant.STRING_NO);
		}
		else
			csvFormat.add("");
		//日時(開始)
		if(info.get(AddListTableDefine.TIME_FROM) instanceof Date)
			csvFormat.add(DateFormat.getDateTimeInstance().format((Date)info.get(AddListTableDefine.TIME_FROM)));
		else
			csvFormat.add("");
		//日時(終了)
		if(info.get(AddListTableDefine.TIME_TO) instanceof Date)
			csvFormat.add(DateFormat.getDateTimeInstance().format((Date)info.get(AddListTableDefine.TIME_TO)));
		else
			csvFormat.add("");
		//説明
		if(info.get(AddListTableDefine.DESCRIPTION) instanceof String)
			csvFormat.add((String)info.get(AddListTableDefine.DESCRIPTION));
		else
			csvFormat.add("");
		
		return csvFormat;
	}
	
	/**
	 * カレンダ実行例外一覧を取得する。<br>
	 * 
	 * @return カレンダ実行例外一覧
	 */
	protected ArrayList getExceptionList(String calendarId) {

		CalendarController cal = EjbConnectionManager.getConnectionManager().getCalendarController();

		ArrayList list = null;
		try {
			list = cal.getAddList(calendarId);
		} catch (Exception e) {
			log.error(Messages.getMsg("ExportTool.ConnectManagerFailed"), e);
			System.exit(14);
		}
		return list;
	}

	/**
	 * カレンダ実行規則一覧を取得する。<br>
	 * 
	 * @return カレンダ実行規則一覧
	 */
	protected ArrayList getRuleList(String calendarId) {

		CalendarController cal = EjbConnectionManager.getConnectionManager().getCalendarController();

		ArrayList list = null;
		try {
			list = cal.getWeekdayList(calendarId);
		} catch (Exception e) {
			log.error(Messages.getMsg("ExportTool.ConnectManagerFailed"), e);
			System.exit(14);
		}
		return list;
	}
	
	/**
	 * カレンダ一覧を取得する。<br>
	 * 
	 * @return カレンダ一覧
	 */
	protected ArrayList getCalendarList() {

		CalendarController cal = EjbConnectionManager.getConnectionManager().getCalendarController();

		ArrayList list = null;
		try {
			list = cal.getCalendarList();
		} catch (Exception e) {
			log.error(Messages.getMsg("ExportTool.ConnectManagerFailed"), e);
			System.exit(14);
		}
		return list;
	}
}