import java.awt.Color;
import java.util.*;

import com.dukascopy.api.*;
import com.dukascopy.api.drawings.IChartObjectFactory;
import com.dukascopy.api.drawings.ILabelChartObject;

public class TickCountStrategy implements IStrategy {
    private IConsole console;
    private IHistory history;
    private IChart chart;

    private ILabelChartObject label;
    int tickCount;
    double price;
    
    @Configurable("Period")
    public Period strategyPeriod = Period.ONE_HOUR;

    @Configurable("Instrument")
    public Instrument strategyInstrument = Instrument.EURUSD;

    double previousValue = 0;

    public void onStart(IContext context) throws JFException {
        this.console = context.getConsole();
        this.history = context.getHistory();
        
        this.chart = context.getChart(strategyInstrument);
    }

    public void onAccount(IAccount account) throws JFException {
    }

    public void onMessage(IMessage message) throws JFException {
    }

    public void onStop() throws JFException {
        print("Stopped!");
    }

    public void onTick(Instrument instrument, ITick tick) throws JFException {
        if (instrument.equals(strategyInstrument)) {
            if(label != null){
                tickCount++;
                label.setText(tickCount+"");
                price = Math.max(tick.getBid(), price);
                label.setPrice(0, Math.max(tick.getBid(), price));
            }
        }
    }

    public void onBar(Instrument instrument, Period period, IBar askBar, IBar bidBar) throws JFException {
        
        if (instrument.equals(strategyInstrument) && period.equals(strategyPeriod)) {
            IBar bar = history.getBar(strategyInstrument, strategyPeriod, OfferSide.BID, 0);
            drawLabel(bar.getTime(), bar.getOpen());
        }
    }

    public void print(Object o) {
        this.console.getOut().println(o.toString());
    }
    
    private void drawLabel(long time, double price) {        
        IChartObjectFactory factory = chart.getChartObjectFactory();
        String key = ("label" + UUID.randomUUID().toString().replace('-', '0'));
        this.label = factory.createLabel(key, time, price);
        label.setText("0");
        label.setColor(Color.BLACK);
        chart.addToMainChart(label);
        
        this.price = price;
        tickCount = 0;
    }
}
