package jforex.test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

import com.dukascopy.api.Configurable;
import com.dukascopy.api.IAccount;
import com.dukascopy.api.IBar;
import com.dukascopy.api.IContext;
import com.dukascopy.api.IMessage;
import com.dukascopy.api.IStrategy;
import com.dukascopy.api.ITick;
import com.dukascopy.api.Instrument;
import com.dukascopy.api.JFException;
import com.dukascopy.api.Period;

public class CalledStrategy3 implements IStrategy {
	
	@Configurable("Period")
	public Period basicTimeFrame = Period.THIRTY_MINS;
	//if false -> print to console
	@Configurable("Print to file")
	public boolean printToFile = false;
	
	private FileOutputStream fileOutputStream; 
	private PrintStream printStream; // declare a print stream object


	@Override
	public void onStart(IContext context) throws JFException {

		//either print to file or to console
		if (printToFile) {
			try {
				final SimpleDateFormat sdf;
        sdf = new SimpleDateFormat("dd-MM-yyyy HH-mm-ss");
				sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
		
				File file = new File ("logFile_" + + sdf.format(new Date()) + ".txt");
				fileOutputStream = new FileOutputStream(file);
				System.out.println("log to file: " + file.getAbsolutePath());
				printStream = new PrintStream(fileOutputStream);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			printStream = System.err;
		}
	}

	@Override
	public void onTick(Instrument instrument, ITick tick) throws JFException { }
	
	private void print(Object o){
		printStream.println(o);
	}

	@Override
	public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException 
	{
		final SimpleDateFormat sdf;
        sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
		sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
		
		String barInfo = "timeframe " + period.toString() + " and bidBar time of " + sdf.format(bidBar.getTime());

		if(period == Period.THIRTY_MINS || period == Period.FOUR_HOURS){
			print(barInfo);
		}
       
	}

	@Override
	public void onMessage(IMessage message) throws JFException {}

	@Override
	public void onAccount(IAccount account) throws JFException {}

	@Override
	public void onStop() throws JFException {
		try {
			if(fileOutputStream!= null)
				fileOutputStream.close();
		} catch (IOException e) {
			e.printStackTrace(System.err);
		}		
	}


}
