package com.dukascopy;

import com.dukascopy.api.*;
import com.dukascopy.api.feed.FeedDescriptor;
import com.dukascopy.api.feed.IFeedDescriptor;
import com.dukascopy.api.plugins.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Callable;
import javax.swing.*;

public class OpenChartBugDemoPlugin extends Plugin {
    private IPluginContext context;

    private String myTabTitle = "Open Chart Bug Demo";
    private JPanel myTab;

    public void onStart(IPluginContext context) throws JFException {
        this.context = context;
        myTab = context.getUserInterface().getLeftTab(myTabTitle);

        ActionListener actionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                IPluginContext context = OpenChartBugDemoPlugin.this.context;
                IFeedDescriptor fd = new FeedDescriptor();

                fd.setInstrument(Instrument.EURUSD);
                fd.setDataType(DataType.TIME_PERIOD_AGGREGATION);
                fd.setPeriod(Period.THIRTY_MINS);
                fd.setOfferSide(OfferSide.BID);

                context.getConsole().getInfo().println("Opening chart for : " + Instrument.EURUSD);
                try {
                    OpenChart openChart = new OpenChart(context, fd);
                    context.executeTask(openChart);
                    
                }
                catch( Throwable ex ) {
                    ex.printStackTrace(context.getConsole().getErr());
                }
            }
        };

        JButton button = new JButton("Open Chart");
        button.addActionListener(actionListener);
        myTab.add(button);
    }


    public void onStop() throws JFException {
        context.getUserInterface().removeLeftTab(myTabTitle);
    }
}

class OpenChart implements Callable<Void> {

    IPluginContext context;
    IFeedDescriptor fd;

    public OpenChart(IPluginContext context, IFeedDescriptor fd) {
        this.context = context;
        this.fd = fd;
    }

    public Void call() throws Exception {
        context.openChart(fd);
        return null;
    }
}
