/*
 * CopyCommand.java Copyright (C) 2020. Daniel H. Huson
 *
 *  (Some files contain contributions from other authors, who are then mentioned separately.)
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package megan.clusteranalysis.commands;

import jloda.swing.commands.ICommand;
import jloda.swing.util.ResourceManager;
import jloda.util.parse.NexusStreamParser;
import megan.clusteranalysis.ClusterViewer;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Collection;

/**
 * copy command
 * Daniel Huson, 7.2010
 */
public class CopyCommand extends CommandBase implements ICommand {

    public CopyCommand() {

    }

    /**
     * get the name to be used as a menu label
     *
     * @return name
     */
    public String getName() {
        return "Copy";
    }

    /**
     * get description to be used as a tooltip
     *
     * @return description
     */
    public String getDescription() {
        return "Copy the current data";
    }

    /**
     * get icon to be used in menu or button
     *
     * @return icon
     */
    public ImageIcon getIcon() {
        return ResourceManager.getIcon("sun/Copy16.gif");
    }

    /**
     * gets the accelerator key  to be used in menu
     *
     * @return accelerator key
     */
    public KeyStroke getAcceleratorKey() {
        return KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx());
    }

    /**
     * parses the given command and executes it
     *
     * @param np
     * @throws java.io.IOException
     */
    @Override
    public void apply(NexusStreamParser np) throws Exception {
        np.matchIgnoreCase("copy what=clusterViewer;");

        ClusterViewer viewer = getViewer();

        StringBuilder buf = new StringBuilder();
        int i = viewer.getTabbedIndex();
        if (i == ClusterViewer.UPGMA_TAB_INDEX) {
            Collection<String> labels = viewer.getUpgmaTab().getGraphView().getSelectedNodeLabels(true);
            for (String label : labels) {
                if (buf.length() > 0)
                    buf.append("\t");
                buf.append(label);
            }
        } else if (i == ClusterViewer.NNET_TAB_INDEX) {
            Collection<String> labels = viewer.getNnetTab().getGraphView().getSelectedNodeLabels(true);
            for (String label : labels) {
                if (buf.length() > 0)
                    buf.append("\t");
                buf.append(label);
            }
        } else if (i == ClusterViewer.PCoA_TAB_INDEX) {
            Collection<String> labels = viewer.getPcoaTab().getGraphView().getSelectedNodeLabels(false);
            for (String label : labels) {
                if (buf.length() > 0)
                    buf.append("\t");
                buf.append(label);
            }
        } else if (i == ClusterViewer.MATRIX_TAB_INDEX) {
            JTable table = viewer.getMatrixTab().getTable();
            for (int row = 0; row < table.getRowCount(); row++) {
                boolean first = true;
                for (int col = 0; col < table.getColumnCount(); col++) {
                    if (!table.getSelectionModel().isSelectionEmpty() || table.isCellSelected(row, col)) {
                        if (first)
                            first = false;
                        else
                            buf.append("\t");
                        buf.append(table.getValueAt(row, col));
                    }
                }
                buf.append("\n");
            }
        }
        /*
        if(buf.length()==0 && viewer.getGraph().getNumberOfNodes()>0) {
                    StringWriter w = new StringWriter();
                    w.write("#NEXUS [generated by MEGAN]\n");
                    w.write("[! Computed using " + viewer.getEcologicalIndex() + " applied to " + viewer.getDataType() + "data]\n");
                    TableModel model = viewer.getMatrixTab().getTable().getModel();
                    w.write("begin taxa;\ndimensions ntax=" + model.getRowCount() + ";\n taxlabels\n");
                    for (int r = 0; r < model.getRowCount(); r++) {
                        w.write("'" + Basic.toCleanName(model.getValueAt(r, 0).toString()) + "'\n");
                    }
                    w.write(";\n");
                    w.write("end;\n");
                    w.write("begin distances;\ndimensions ntax=" + model.getRowCount() + ";\n");
                    w.write("format triangle=both diagonal labels;\nmatrix\n");
                    for (int r = 0; r < model.getRowCount(); r++) {
                        w.write("'" + Basic.toCleanName(model.getValueAt(r, 0).toString()) + "'");
                        for (int c = 1; c < model.getColumnCount(); c++) {
                            w.write(" " + model.getValueAt(r, c));
                        }
                        w.write("\n");
                    }
                    w.write(";\n");
                    w.write("end;\n");
            buf.append(w.toString());
        }
        */
        if (buf.length() > 0) {
            StringSelection stringSelection = new StringSelection(buf.toString());
            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, stringSelection);
        }
    }

    /**
     * is this a critical command that can only be executed when no other command is running?
     *
     * @return true, if critical
     */
    public boolean isCritical() {
        return false;
    }

    /**
     * get command-line usage description
     *
     * @return usage
     */
    @Override
    public String getSyntax() {
        return "copy what=<clusterViewer>;"; // not a command-line command
    }

    /**
     * is the command currently applicable? Used to set enable state of command
     *
     * @return true, if command can be applied
     */
    public boolean isApplicable() {
        /*
        NetworkViewer networkViewer = (NetworkViewer) getViewer();
        return (networkViewer.getTabbedIndex() == 0 && networkViewer.getSelectedNodes().size() > 0)
                || (networkViewer.getTabbedIndex() == 1 && networkViewer.getPlotTab().getGraphView().getSelectedNodes().size() > 0)
                || (networkViewer.getTabbedIndex() == 2);
        */
        return true;
    }

    /**
     * action to be performed
     *
     * @param ev
     */
    @Override
    public void actionPerformed(ActionEvent ev) {
        executeImmediately("copy what=clusterViewer;");
    }
}
