/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * http://aipostyle.com/
 * 
 * Copyright(C) 2010 avanza Co.,Ltd. All rights reserved.
 * http://www.avnz.co.jp/
 * 
 * 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; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * 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.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.aimluck.eip.modules.screens;

import java.io.ByteArrayOutputStream;
import java.util.Calendar;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.fortuna.ical4j.model.Recur;
import net.fortuna.ical4j.model.WeekDay;
import net.fortuna.ical4j.model.property.Clazz;
import net.fortuna.ical4j.model.property.Created;
import net.fortuna.ical4j.model.property.Description;
import net.fortuna.ical4j.model.property.LastModified;
import net.fortuna.ical4j.model.property.Location;
import net.fortuna.ical4j.model.property.Method;
import net.fortuna.ical4j.model.property.RRule;
import net.fortuna.ical4j.model.property.Uid;

import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;

import com.aimluck.eip.util.ALEipUtils;

/**
 * iCalenndar形式のスケジュールデータ(サンプル)のダウンロードを処理するクラスです。 <br />
 * 
 */
public class CoordinationForGoogleCalICSSampleFileScreen extends ALVelocityScreen {
  /** logger */
  private static final JetspeedLogger logger = JetspeedLogFactoryService
      .getLogger(CoordinationForGoogleCalICSSampleFileScreen.class.getName());


  /**
   * @see org.apache.turbine.modules.screens.RawScreen#doOutput(org.apache.turbine.util.RunData)
   */
  @Override
  protected void doOutput(RunData rundata, Context context) throws Exception {
    ServletOutputStream out = null;

    try {

      HttpServletResponse response = rundata.getResponse();
      response.setHeader("Content-disposition", "attachment; filename=SAMPLE.ics");
      response.setHeader("Cache-Control", "no-cache");
      response.setHeader("Pragma", "No-cache");
      // ファイル内容の出力
      out = response.getOutputStream();
      out.write(makeSampleCalendar().getBytes("UTF-8"));
      out.flush();
      out.close(); 

    } catch (Exception ex) {
      logger.error("[CoordinationForGoogleCalICSSampleFileScreen] Exception.", ex);
      ALEipUtils.redirectDBError(rundata);
    }
  }
  
  
  protected String makeSampleCalendar(){
    try{
      
      String calendarAsString = null;
    
      // カレンダーの生成 【固定値】
      net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();
      calendar.getProperties().add(new net.fortuna.ical4j.model.property.ProdId("-//avanza Co.,Ltd.//Aipo5 Schedule Portlet//JP"));
      calendar.getProperties().add(net.fortuna.ical4j.model.property.CalScale.GREGORIAN);
      calendar.getProperties().add(net.fortuna.ical4j.model.property.Version.VERSION_2_0);
      calendar.getProperties().add(new Method("PUBLISH"));

      //タイムゾーンの設定
      net.fortuna.ical4j.model.TimeZoneRegistry registry = 
        net.fortuna.ical4j.model.TimeZoneRegistryFactory.getInstance().createRegistry();
      net.fortuna.ical4j.model.TimeZone timezoneAsIcalTimeZone = registry.getTimeZone("Asia/Tokyo");
      net.fortuna.ical4j.model.component.VTimeZone tz = timezoneAsIcalTimeZone.getVTimeZone();
     
      //イベントの作成(1)
      net.fortuna.ical4j.model.component.VEvent sampleEv 
        = new net.fortuna.ical4j.model.component.VEvent();
      // タイムゾーン Asia/Tokyo　【固定値】
      sampleEv.getProperties().add(tz.getTimeZoneId());
    
      //件名・タイトル
      net.fortuna.ical4j.model.property.Summary summary 
        = new net.fortuna.ical4j.model.property.Summary("サンプル１");
      sampleEv.getProperties().add(summary);
    
      //パラメータリストの作成
      net.fortuna.ical4j.model.ParameterList datepara 
        = new net.fortuna.ical4j.model.ParameterList(); 
      //パラメータリストにバリューをセット
      datepara.add(net.fortuna.ical4j.model.parameter.Value.DATE);
    
      
      //イベントに開始時間のセット
      
      Calendar sample_start = Calendar.getInstance();
      sample_start.set(2010, 02, 01);
      net.fortuna.ical4j.model.property.DtStart dts 
        = new net.fortuna.ical4j.model.property.DtStart
        (datepara, new net.fortuna.ical4j.model.Date(sample_start.getTime().getTime()));
      sampleEv.getProperties().add(dts);              

      //イベントに終了時間のセット
      Calendar sample_end = Calendar.getInstance();
      sample_end.set(2010, 02, 30); 
      net.fortuna.ical4j.model.property.DtEnd dte 
        = new net.fortuna.ical4j.model.property.DtEnd
        (datepara, new net.fortuna.ical4j.model.Date(sample_end.getTime().getTime()));
      sampleEv.getProperties().add(dte);

   
      //イベントに作成日を追加
      Calendar sample_created = Calendar.getInstance();
      net.fortuna.ical4j.model.DateTime sample_icreated 
        = new net.fortuna.ical4j.model.DateTime();
      sample_icreated.setTime(sample_created.getTime().getTime());
      sample_icreated.setTimeZone(timezoneAsIcalTimeZone);
      sampleEv.getProperties().add(new Created(sample_icreated));   
      
      //イベントに更新日を追加
      sampleEv.getProperties().add(new LastModified(sample_icreated));  

      //UID
      sampleEv.getProperties().add(new Uid("Aipo:" + "avanza:" + "sample_schedule_id001"));
      
      //公開フラグ
      sampleEv.getProperties().add(new Clazz("PUBLIC"));
      
      //場所
      sampleEv.getProperties().add(new Location("場所はここに記述"));
          
      //コメント
      sampleEv.getProperties().add(new Description("コメントはここに記述"));
      
      
      
      
      //イベントの作成(2)
      net.fortuna.ical4j.model.component.VEvent sampleEv2 
        = new net.fortuna.ical4j.model.component.VEvent();
      // タイムゾーン Asia/Tokyo　【固定値】
      sampleEv2.getProperties().add(tz.getTimeZoneId());
    
      //件名・タイトル
      net.fortuna.ical4j.model.property.Summary summary2 
        = new net.fortuna.ical4j.model.property.Summary("サンプル２");
      sampleEv2.getProperties().add(summary2);
    
      //イベントに開始時間のセット
      Calendar sample_start2 = Calendar.getInstance();
      sample_start2.set(2010, 03, 01, 13, 00, 00);

      net.fortuna.ical4j.model.property.DtStart dts2 
        = new net.fortuna.ical4j.model.property.DtStart
        (new net.fortuna.ical4j.model.DateTime(sample_start2.getTime()));
      dts2.setTimeZone(timezoneAsIcalTimeZone);
      sampleEv2.getProperties().add(dts2);              

      //イベントに終了時間のセット
      Calendar sample_end2 = Calendar.getInstance();
      sample_end2.set(2010, 03, 01, 17, 00, 00);      
      net.fortuna.ical4j.model.property.DtEnd dte2 
        = new net.fortuna.ical4j.model.property.DtEnd
        (new net.fortuna.ical4j.model.DateTime(sample_end2.getTime()));
      dte2.setTimeZone(timezoneAsIcalTimeZone);
      sampleEv2.getProperties().add(dte2);

      //イベントの作成日をセット
      sampleEv2.getProperties().add(new Created(sample_icreated));
    
      //イベントに更新日を追加
      sampleEv2.getProperties().add(new LastModified(sample_icreated)); 
      
      //RRuleのセット      
      Recur recur = new Recur("FREQ=WEEKLY");
      recur.getDayList().add(WeekDay.TH);
      RRule rrule = new RRule(recur);
      sampleEv2.getProperties().add(rrule);
   
      //UID
      sampleEv2.getProperties().add(new Uid("Aipo:" + "avanza:" +  "sample_schedule_id002"));
    
      //公開フラグ
      sampleEv2.getProperties().add(new Clazz("PRIVATE"));
      
      // カレンダにイベントを追加
      calendar.getComponents().add(sampleEv); 
      calendar.getComponents().add(sampleEv2); 
      // カレンダを文字列として書き出す
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      net.fortuna.ical4j.data.CalendarOutputter outputter 
        = new net.fortuna.ical4j.data.CalendarOutputter();
      outputter.output(calendar, baos);

      calendarAsString = baos.toString("UTF-8");           
      
      return calendarAsString;
    
    }catch(Exception ex){
      logger.error("[CoordinationForGoogleCalICSSampleFileScreen] Exception.", ex);
    }
      return null;
  }
}
