package jimena.gui.charts;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import jimena.binaryrn.NetworkNode;
import jimena.binaryrn.RegulatoryNetwork;
import jimena.gui.main.HasActivatableNodes;
import jimena.libs.TxtFileChooser;

/**
 * A windows that displays the logs of the nodes.
 * 
 * @author Stefan Karl, Department of Bioinformatics, University of Würzburg, stefan[dot]karl[at]uni-wuerzburg[dot]de
 * 
 */
public class ChartsWindow extends JFrame implements HasActivatableNodes {
    private static final long serialVersionUID = 4806615342528853734L;

    private NodeList nodeList;

    /**
     * Creates a new windows that displays the logs of the nodes.
     * 
     * @param network
     *            The network whose logs are to be displayed
     */
    public ChartsWindow(RegulatoryNetwork network) {
        // Set up the window and the layout
        super("Charts Window");
        setIconImage(new ImageIcon("images" + File.separator + "chart16.png").getImage());
        JPanel panel = new JPanel(new BorderLayout());

        JPanel nodesListPanel = new JPanel(new BorderLayout());

        nodeList = new NodeList(network);
        JScrollPane nodesScrollPane = new JScrollPane(nodeList) {
            private static final long serialVersionUID = -628832940977979418L;

            // This ScrollPane may not be a validate root since we want the revalidates to propagate to the JFrame
            @Override
            public boolean isValidateRoot() {
                return false;
            }
        };

        nodesListPanel.add(nodesScrollPane, BorderLayout.CENTER);

        // Create a button to save the data from the logs to a tab separated file.
        JButton exportButton = new JButton("Export Selected", new ImageIcon("images" + File.separator + "save16.png"));
        exportButton.setToolTipText("Exports the data to a text-file.");
        exportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                StringBuilder result = new StringBuilder();

                NetworkNode[] nodes = ChartsWindow.this.nodeList.getSelectedNodes();

                if (nodes.length == 0) {
                    JOptionPane.showMessageDialog(null, "Please select some nodes in the chartes window. ", "No nodes selected",
                            JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE);
                    return;
                }

                result.append("time\t");
                for (int i = 0; i < nodes.length; i++) {
                    result.append(nodes[i].getName() + "\t");
                }
                result.append("\n");

                for (int j = 0; j < nodes[0].getLog().size(); j++) {
                    result.append(nodes[0].getLog().get(j).getX() + "\t");
                    for (int i = 0; i < nodes.length; i++) {
                        result.append(nodes[i].getLog().get(j).getY());
                        if(i!=nodes.length-1){
                            result.append("\t");
                        }
                    }
                    if (j != nodes[0].getLog().size() - 1) {
                        result.append("\n");
                    }
                }

                TxtFileChooser.writeToTextFile(result.toString(), ChartsWindow.this);
            }
        });
        nodesListPanel.add(exportButton, BorderLayout.SOUTH);

        panel.add(nodesListPanel, BorderLayout.EAST);

        JPanel chartsPanel = new ChartsPanel(network, nodeList);
        panel.add(chartsPanel, BorderLayout.CENTER);

        setContentPane(panel);

        setMinimumSize(new Dimension(600, 400));
    }

    @Override
    public void activateNode(int nodeIndex) {
        // This method is called if the user right clicks on a node in the main window
        // The charts frame is shown and the visibility of the selected node is switched
        ArrayList<Integer> selectedIndices = new ArrayList<Integer>();
        for (Integer index : nodeList.getSelectedIndices()) {
            selectedIndices.add(index);
        }

        if (selectedIndices.contains(nodeIndex)) {
            selectedIndices.remove((Integer) nodeIndex);
        } else {
            selectedIndices.add((Integer) nodeIndex);
        }

        int[] arraySelectedIndices = new int[selectedIndices.size()];
        for (int i = 0; i < selectedIndices.size(); i++) {
            arraySelectedIndices[i] = selectedIndices.get(i);
        }

        nodeList.setSelectedIndices(arraySelectedIndices);

        if (!isVisible()) {
            setVisible(true);
        }
    }
}
