/*     
 * This is a test programm only, do not use for trading! 
 * It checks getBars(Instrument instrument,
 *                            Period period,
 *                            OfferSide side,
 *                            Filter filter,
 *                            int numberOfCandlesBefore,
 *                            long time,
 *                            int numberOfCandlesAfter)
 * method of IHistory
 * At current JForex version it give wrong results!
 *
 * (c) Stash GmbH Muenchen / Germany, July 23rd 2012
 *     www.stash.de
 *     Author: Bernhard Schicht
 *     Email: exp@stash.de
 */
package jforex;

import java.util.*;
import java.text.SimpleDateFormat;
import com.dukascopy.api.*;

public class CustomPeriodBug implements IStrategy {
    private IEngine engine;
    private IConsole console;
    private IHistory history;
    private IContext context;
    private IIndicators indicators;
    private IUserInterface userInterface;
    private Period twoMin = null;
    
    public void onStart(IContext context) throws JFException {
        this.engine = context.getEngine();
        this.console = context.getConsole();
        this.history = context.getHistory();
        this.context = context;
        this.indicators = context.getIndicators();
        this.userInterface = context.getUserInterface();
        twoMin = Period.createCustomPeriod(Unit.Minute, 2);
    }

    public void onAccount(IAccount account) throws JFException {
    }

    public void onMessage(IMessage message) throws JFException {
    }

    public void onStop() throws JFException {
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
    }
    
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
        int BARSAMOUNT = 3;
        long time = history.getBarStart(twoMin,  history.getLastTick(instrument).getTime());
        long bartime = history.getBarStart(twoMin,  time);
        List<IBar> barsList = history.getBars(instrument, twoMin,  OfferSide.ASK, Filter.WEEKENDS,BARSAMOUNT, bartime, 0);
        
        Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
        for (int t = 0 ; t < barsList.size() ; t++){
            cal.setTimeInMillis(barsList.get(t).getTime());
            console.getOut().println("bar"+t+": "+getGMTString(cal.getTime()));            
        }

    }
    
    public static String getGMTString(long milis){
      Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
      cal.setTimeInMillis(milis);
      return getGMTString(cal.getTime());
    }
    public static String getGMTString(Date date){      
      //     Festlegung des Formats:
      SimpleDateFormat df = new SimpleDateFormat( "dd-MM-yyyy HH:mm:ss.SSS z" );
      df.setTimeZone(TimeZone.getTimeZone("GMT"));            
      return df.format(date);      
    }
}