//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package de.ugoe.cs.autoquest.ui.swt.commands;

import java.awt.Frame;
import java.util.LinkedList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.awt.SWT_AWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.ui.RectangleEdge;

import de.ugoe.cs.autoquest.CommandHelpers;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskModel;
import de.ugoe.cs.autoquest.ui.swt.TaskTreePlotUtils;
import de.ugoe.cs.util.console.Command;
import de.ugoe.cs.util.console.GlobalDataContainer;

/**
 * <p>
 * Command to show sequences.
 * </p>
 * 
 * @author Jeffrey Hall, Steffen Herbold
 */
public class CMDplotTaskTreeCoverage implements Command {

    /*
     * (non-Javadoc)
     * 
     * @see de.ugoe.cs.util.console.Command#help()
     */
    @Override
    public String help() {
        return "plotTaskTreeCoverage <taskTreeNames>";
    }

    /*
     * (non-Javadoc)
     * 
     * @see de.ugoe.cs.util.console.Command#run(java.util.List)
     */
    @Override
    public void run(List<Object> parameters) {
        List<Integer> taskTreeGroups = new LinkedList<>();
        int group = 0;
        
        List<String> taskTreeNames = new LinkedList<>();
        try {
            for (Object param : parameters) {
                if ("#".equals(param)) {
                    group++;
                }
                else {
                    taskTreeNames.add((String) param);
                    taskTreeGroups.add(group);
                }
            }
        }
        catch (Exception e) {
            throw new IllegalArgumentException();
        }

        List<ITaskModel> taskModels = new LinkedList<>();
        
        for (String taskTreeName : taskTreeNames) {
            Object dataObject = GlobalDataContainer.getInstance().getData(taskTreeName);
            if (dataObject == null) {
                CommandHelpers.objectNotFoundMessage(taskTreeName);
                return;
            }
            if (!(dataObject instanceof ITaskModel)) {
                CommandHelpers.objectNotType(taskTreeName, "ITaskModel");
                return;
            }
            
            taskModels.add((ITaskModel) dataObject);
        }

        // create the chart
        final JFreeChart chart = TaskTreePlotUtils.createPlot
            (TaskTreePlotUtils.CUMULATIVE_TASK_COVERAGE_PLOT, taskModels, taskTreeNames,
             taskTreeGroups);
        
        final int width;
        if (chart.getLegend() != null) {
            width = 700;
            chart.getLegend().setPosition(RectangleEdge.RIGHT);
        }
        else {
            width = 500;
        }
        
        final Shell shell = new Shell(SWT.SHELL_TRIM | SWT.BORDER | SWT.APPLICATION_MODAL);
        shell.layout();
        shell.setSize(width, 500);
        shell.setLayout(new GridLayout(2, false));
        
        Composite parent = new Composite(shell, SWT.EMBEDDED);
        parent.setLayout(new GridLayout(1, false));
        parent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
        
        Frame chartFrame = SWT_AWT.new_Frame(parent);
        chartFrame.setLayout(new java.awt.GridLayout());
        
        chartFrame.add(new ChartPanel(chart));

        Button btnExport = new Button(shell, SWT.NONE);
        btnExport.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                try {
                    FileDialog dialog = new FileDialog(shell, SWT.SAVE);
                    dialog.setFilterExtensions(new String [] {"*.pdf"});
                    
                    TaskTreePlotUtils.saveChartToPDF(chart, dialog.open(), width, 500);
                }
                catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        btnExport.setText("export to PDF");

        Button btnClose = new Button(shell, SWT.NONE);
        btnClose.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                shell.dispose();
            }
        });
        btnClose.setText("close");

        shell.open();
        shell.layout();
        Display display = shell.getDisplay();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        
        shell.dispose();
    }
}
