package jforex;
import java.util.*;
import java.io.*;
import java.text.*;
import com.dukascopy.api.*;
 
@RequiresFullAccess
public class DownloadtoCSV34 implements IStrategy {
    @Configurable("Period")
    public Period period=Period.ONE_HOUR;
    @Configurable("Instrument")
    public Instrument instrument=Instrument.EURUSD;
    @Configurable("OfferSide")
    public OfferSide offerSide=OfferSide.BID;
      
    //private DecimalFormat priceFormat;
    private SimpleDateFormat gmtsdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private SimpleDateFormat gmtsdf2=new SimpleDateFormat("yyyyMMddHHmm");
    private SimpleDateFormat gmtsdf3=new SimpleDateFormat("yyyyMMdd");
     
    private String startDateStr="2012-04-07 00:00:00";
    private int numOfWeeks=3;
     
    private IEngine engine;
    private IConsole console; // use
    private IHistory history; // use
    private IContext context;
    private IIndicators indicators;
    private IUserInterface userInterface;
     
    //@Override
    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();
         
        gmtsdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        gmtsdf2.setTimeZone(TimeZone.getTimeZone("GMT"));// the default is GMT+8
        gmtsdf3.setTimeZone(TimeZone.getTimeZone("GMT"));// the default is GMT+8
        //priceFormat=new DecimalFormat("0.#####");
      
        long startDate=0;
        try{
            startDate=gmtsdf.parse(startDateStr).getTime();
        }catch(ParseException el){
            //stop strategy
            console.getErr().println(el);
            context.stop();
            return;
        }
         
        long startBarTime=history.getBarStart(period, startDate);// minus one to exclude the crrunt time.
        long startBarTime0;
        for (int i=0; i<numOfWeeks; i++){
           startBarTime0=startBarTime;
           startBarTime=startBarTime-24*7*3600*1000;
           singleInstrWeekprint(instrument,startBarTime,startBarTime0);
        }
        
    }
    @Override
    public void onAccount(IAccount account) throws JFException {}
    @Override
    public void onMessage(IMessage message) throws JFException {}
    @Override
    public void onStop() throws JFException {}
    @Override
    public void onTick(Instrument instrument, ITick tick) throws JFException {}
    @Override
    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {}
 
    private void singleInstrWeekprint(Instrument instrument,long startBarTime,long startBarTime0){
        int k;
        int r=0;
        String FILE_NAME;
        String path="D:\\JforexTemp\\";
        FileWriter fstream;
        BufferedWriter out = null;
        Calendar c = Calendar.getInstance();//
        c.setTimeZone(TimeZone.getTimeZone("GMT"));
        try{
            //List<IBar> bars=history.getBars(instrument,period,OfferSide.BID,endBarTime,startBarTime);
            List<IBar> bars=history.getBars(instrument,Period.ONE_HOUR,OfferSide.BID,Filter.WEEKENDS,startBarTime,startBarTime0);
            print(String.format("start to %s,  end to %s, retrieved bar count: %s",  gmtsdf.format(startBarTime),gmtsdf.format(startBarTime0), bars.size()));
            for(IBar bar:bars){
                c.setTimeInMillis(bar.getTime());
                k=c.get(Calendar.DAY_OF_WEEK);// The day-of-week is an integer value where 1 is Sunday, 2 is Monday, ..., and 7 is Saturday
                if (r==0){ // set the filename at the first bar.
                    FILE_NAME=path+"WriteTickToFile_"+instrument.toString().replace("/","")+"_"+gmtsdf3.format(c)+".csv";
                    try{
                          //fstream=new FileWriter(FILE_NAME,true); // append is allowed
                          fstream=new FileWriter(FILE_NAME,false);
                          out=new BufferedWriter(fstream);
                    }catch (IOException e){
                          print("Can not initialize output stream; stopping the strategy");
                          context.stop();
                    }
                    r=1;
                }
                try{
                      //out.append("1"+","+"2.3"+"\n");
                      out.write(gmtsdf2.format(bar.getTime())+","+k+","+bar.getOpen()+","+bar.getHigh()+","+bar.getLow()+","+
                          bar.getClose()+","+bar.getVolume()+"\r\n");
                }catch (IOException e){
                      print("File write error");
                      e.printStackTrace();
                }
                 
            }
            try{
                  if(out!=null){
                      out.flush();
                      out.close();
                  }
            }catch(IOException e){
                  print("can not close output stream");
                  e.printStackTrace();
            }
            //print(String.format("end of %s,  retrieved bar count: %s",  gmtsdf.format(startBarTime), bars.size()));
       }catch(Exception e){
          console.getErr().println(e.getMessage());
          e.printStackTrace(console.getErr());
          context.stop();
       }
    }
 
    private void print(Object o){
        console.getOut().println(o);
    }
}