//   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;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.GridData;

import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskTree;
import de.ugoe.cs.autoquest.usageprofiles.FirstOrderMarkovModel;
import de.ugoe.cs.autoquest.usageprofiles.IDotCompatible;
import de.ugoe.cs.autoquest.usageprofiles.IStochasticProcess;
import de.ugoe.cs.util.console.CommandExecuter;
import de.ugoe.cs.util.console.GlobalDataContainer;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

public class ModelsTabComposite extends Composite {

    /** */
    List modelList;

    /** */
    Button btnShow;

    /** */
    Button btnDelete_1;

    /** */
    Button btnGenSequences;

    /** */
    Button btnProperties;

    /** */
    Button btnCreateDot;
    
    /**
     * Create the composite.
     * 
     * @param parent
     * @param style
     */
    public ModelsTabComposite(Composite parent, int style) {
        super(parent, style);
        createContents();
    }

    /**
     * 
     */
    private void createContents() {
        setLayout(new GridLayout(5, false));

        modelList = new List(this, SWT.BORDER | SWT.V_SCROLL);
        modelList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 5, 1));
        modelList.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                String[] selectedStrings = modelList.getSelection();
                if (selectedStrings.length == 1) {
                    btnShow.setEnabled(true);
                    btnDelete_1.setEnabled(true);
                    Object obj = GlobalDataContainer.getInstance().getData(selectedStrings[0]);
                    if (obj instanceof IStochasticProcess) {
                        btnGenSequences.setEnabled(true);
                        btnProperties.setEnabled(true);
                        btnCreateDot.setEnabled(true);
                    }
                    else {
                        btnGenSequences.setEnabled(false);
                        btnProperties.setEnabled(false);
                        btnCreateDot.setEnabled(false);
                    }
                }
                else if (selectedStrings.length > 1) {
                    btnShow.setEnabled(false);
                    btnDelete_1.setEnabled(true);
                    btnProperties.setEnabled(false);
                    btnCreateDot.setEnabled(false);
                    
                    boolean enableSequenceGeneration = true;
                    for (String selectedString : selectedStrings) {
                        Object obj = GlobalDataContainer.getInstance().getData(selectedString);
                        if (!(obj instanceof IStochasticProcess)) {
                            enableSequenceGeneration = false;
                            break;
                        }
                    }
                    btnGenSequences.setEnabled(enableSequenceGeneration);
                }
            }
        });

        btnShow = new Button(this, SWT.NONE);
        btnShow.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                String[] selectedStrings = modelList.getSelection();
                if (selectedStrings.length == 0) {
                    SWTHelpers.noSelectionError(getShell());
                    return;
                }
                else if (selectedStrings.length > 1) {
                    SWTHelpers.moreThanOneSelectedError(getShell());
                    return;
                }
                
                Object obj = GlobalDataContainer.getInstance().getData(selectedStrings[0]);
                
                if (obj instanceof FirstOrderMarkovModel) {
                    String command = "showMarkovModel " + selectedStrings[0];
                    CommandExecuter.getInstance().exec(command);
                }
                else if (obj instanceof ITaskTree) {
                    ShowTaskTreeDialog showTaskTreeDialog = new ShowTaskTreeDialog
                        (getShell(), SWT.NONE, (ITaskTree) obj, selectedStrings[0]);
                    showTaskTreeDialog.open();
                }
                else {
                    MessageBox messageBox = new MessageBox(getShell(), SWT.NONE);
                    messageBox.setText("Feature Not Available");
                    messageBox.setMessage("This feature is currently only available for " +
                                          "first-order Markov models and task trees.");
                    messageBox.open();
                }
            }
        });
        btnShow.setText("Visualize");
        btnShow.setEnabled(false);

        btnDelete_1 = new Button(this, SWT.NONE);
        btnDelete_1.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                if (SWTHelpers.deleteSelectedFromStorage(modelList)) {
                    updateModelList();
                }
                else {
                    SWTHelpers.noSelectionError(getShell());
                }
            }
        });
        btnDelete_1.setText("Delete");
        btnDelete_1.setEnabled(false);

        btnGenSequences = new Button(this, SWT.NONE);
        btnGenSequences.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                String[] selectedStrings = modelList.getSelection();
                if (selectedStrings.length == 0) {
                    SWTHelpers.noSelectionError(getShell());
                    return;
                }
                
                boolean enableSequenceGeneration = true;
                for (String selectedString : selectedStrings) {
                    Object obj = GlobalDataContainer.getInstance().getData(selectedString);
                    if (!(obj instanceof IStochasticProcess)) {
                        enableSequenceGeneration = false;
                        break;
                    }
                }
                
                if (enableSequenceGeneration) {
                    GenerateSequencesDialog generateSequencesDialog =
                        new GenerateSequencesDialog(getShell(), SWT.NONE);
                    generateSequencesDialog.setProcessName(selectedStrings[0]);
                    generateSequencesDialog.open();
                }
                else {
                    MessageBox messageBox = new MessageBox(getShell(), SWT.NONE);
                    messageBox.setText("Feature Not Available");
                    messageBox.setMessage("This feature is not available for task trees. Please " +
                                          "deselect the selected task tree(s)!");
                    messageBox.open();
                }
            }
        });
        btnGenSequences.setText("Gen. Sequences");
        btnGenSequences.setEnabled(false);

        btnProperties = new Button(this, SWT.NONE);
        btnProperties.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                String[] selectedStrings = modelList.getSelection();
                if (selectedStrings.length == 0) {
                    SWTHelpers.noSelectionError(getShell());
                    return;
                }
                else if (selectedStrings.length > 1) {
                    SWTHelpers.moreThanOneSelectedError(getShell());
                    return;
                }
                
                Object obj = GlobalDataContainer.getInstance().getData(selectedStrings[0]);
                
                if (obj instanceof IStochasticProcess) {
                    IStochasticProcess process = (IStochasticProcess) obj;
                    ModelPropertiesDialog modelPropertiesDialog =
                        new ModelPropertiesDialog(getShell(), SWT.NONE);
                    modelPropertiesDialog.setStochasticProcess(process);
                    modelPropertiesDialog.open();
                }
                else {
                    MessageBox messageBox = new MessageBox(getShell(), SWT.NONE);
                    messageBox.setText("Feature Not Available");
                    messageBox.setMessage("The feature is currently only available for " +
                                          "stochastic processes. Please select a model that " +
                                          "is a stochastic process.");
                    messageBox.open();
                }
            }
        });
        btnProperties.setText("Properties");
        btnProperties.setEnabled(false);

        btnCreateDot = new Button(this, SWT.NONE);
        btnCreateDot.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                String[] selectedStrings = modelList.getSelection();
                if (selectedStrings.length == 0) {
                    SWTHelpers.noSelectionError(getShell());
                    return;
                }
                else if (selectedStrings.length > 1) {
                    SWTHelpers.moreThanOneSelectedError(getShell());
                    return;
                }
                
                Object obj = GlobalDataContainer.getInstance().getData(selectedStrings[0]);
                
                if (obj instanceof IStochasticProcess) {
                    String command;
                    if (obj instanceof IDotCompatible) {
                        command = "printDot ";
                    }
                    else {
                        command = "printTrieDot ";
                    }
                    command += selectedStrings[0];
                    CommandExecuter.getInstance().exec(command);
                }
                else {
                    MessageBox messageBox = new MessageBox(getShell(), SWT.NONE);
                    messageBox.setText("Feature Not Available");
                    messageBox.setMessage("The feature is currently only available for " +
                                          "stochastic processes. Please select a model that " +
                                          "is a stochastic process.");
                    messageBox.open();
                }
            }
        });
        btnCreateDot.setText("Create DOT");
        btnCreateDot.setEnabled(false);
    }

    /**
     * 
     */
    @Override
    protected void checkSubclass() {
        // Disable the check that prevents subclassing of SWT components
    }

    /**
     * 
     */
    public void updateModelList() {
        modelList.removeAll();
        for (String key : GlobalDataContainer.getInstance().getAllKeys()) {
            if ((GlobalDataContainer.getInstance().getData(key) instanceof IStochasticProcess) ||
                (GlobalDataContainer.getInstance().getData(key) instanceof ITaskTree))
            {
                modelList.add(key);
            }
        }
    }

}
