/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on ----
!  AUTHOR(S): KOGA, Junichiro
!  File : ExcelAdapter.java
!  
!  Contact address :  Phase System Consortium
!                     E-mail: phase_system@nims.go.jp URL https://azuma.nims.go.jp
!
!
!   Since 2002, this program set had been intensively developed as a part of the following 
!  national projects supported by the Ministry of Education, Culture, Sports, Science and
!  Technology (MEXT) of Japan; "Frontier Simulation Software for Industrial Science
!  (FSIS)" from 2002 to 2005, "Revolutionary Simulation Software (RSS21)" from 2006 to
!  2008. "Research and Development of Innovative Simulation Software (RISS)" from 2008
!  to 2013. These projects is lead by the Center for Research on Innovative Simulation 
!  Software (CISS), the Institute of Industrial Science (IIS), the University of Tokyo.
!   Since 2013, this program set has been further developed centering on PHASE System
!  Consortium. 
!   The activity of development of this program set has been supervised by Takahisa Ohno.
!
!=======================================================================
 */
package ciss.phase_viewer.common;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.StringTokenizer;

import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;

public class ExcelAdapter implements ActionListener {
    private String rowstring;
    private String value;
    private Clipboard system;
    private StringSelection stsel;
    private JTable jTable1;

    /**
     * 引数で取得したJTableオブジェクトに対してアクションリスナーを配備することによってコピーペーストを 実現する.
     * 基本的にはコンストラクターですべての作業を行うので, 本クラスの使用者はそれ以上明示的に行う 必要はない.
     * 
     * @param myJTable
     *            コピーペースト機能を付けたいJTable.
     */

    public ExcelAdapter(JTable myJTable) {
        jTable1 = myJTable;
        KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C,
                ActionEvent.CTRL_MASK, false);
        // Identifying the copy KeyStroke user can modify this
        // to copy on some other Key combination.
        KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,
                ActionEvent.CTRL_MASK, false);
        // Identifying the Paste KeyStroke user can modify this
        // to copy on some other Key combination.
        jTable1.registerKeyboardAction(this, "Copy", copy,
                JComponent.WHEN_FOCUSED);

        jTable1.registerKeyboardAction(this, "Paste", paste,
                JComponent.WHEN_FOCUSED);
        system = Toolkit.getDefaultToolkit().getSystemClipboard();
    }

    /**
     * このクラスに格納されたJTableオブジェクトへの参照を返す.
     * 
     * @return JTableオブジェクト.
     */
    public JTable getJTable() {
        return jTable1;
    }

    /**
     * このクラスに格納するJTableオブジェクトを設定する.
     * 
     * @param jTable1
     *            JTableオブジェクト.
     */
    public void setJTable(JTable jTable1) {
        this.jTable1 = jTable1;
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().compareTo("Copy") == 0) {
            StringBuffer sbf = new StringBuffer();
            // Check to ensure we have selected only a contiguous block of
            // cells
            int numcols = jTable1.getSelectedColumnCount();
            int numrows = jTable1.getSelectedRowCount();
            int[] rowsselected = jTable1.getSelectedRows();
            int[] colsselected = jTable1.getSelectedColumns();
            if (!((numrows - 1 == rowsselected[rowsselected.length - 1]
                    - rowsselected[0] && numrows == rowsselected.length) && (numcols - 1 == colsselected[colsselected.length - 1]
                    - colsselected[0] && numcols == colsselected.length))) {
                JOptionPane.showMessageDialog(null, "Invalid Copy Selection",
                        "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE);
                return;
            }
            for (int i = 0; i < numrows; i++) {
                for (int j = 0; j < numcols; j++) {
                    sbf.append(jTable1.getValueAt(rowsselected[i],
                            colsselected[j]));
                    if (j < numcols - 1)
                        sbf.append("\t");
                }
                sbf.append("\n");
            }
            stsel = new StringSelection(sbf.toString());
            system = Toolkit.getDefaultToolkit().getSystemClipboard();
            system.setContents(stsel, stsel);
        }
        if (e.getActionCommand().compareTo("Paste") == 0) {
            System.out.println("Trying to Paste");
            int startRow = (jTable1.getSelectedRows())[0];
            int startCol = (jTable1.getSelectedColumns())[0];
            try {
                String trstring = (String) (system.getContents(this)
                        .getTransferData(DataFlavor.stringFlavor));
                System.out.println("String is:" + trstring);
                StringTokenizer st1 = new StringTokenizer(trstring,
                        System.getProperty("line.separator"));
                for (int i = 0; st1.hasMoreTokens(); i++) {
                    rowstring = st1.nextToken();
                    StringTokenizer st2 = new StringTokenizer(rowstring, "\t");
                    if (st2.countTokens() <= 1) {
                        st2 = new StringTokenizer(rowstring, " ");
                    }
                    if (st2.countTokens() <= 1) {
                        st2 = new StringTokenizer(rowstring, ",");
                    }
                    for (int j = 0; st2.hasMoreTokens(); j++) {
                        value = (String) st2.nextToken();
                        if (startRow + i < jTable1.getRowCount()
                                && startCol + j < jTable1.getColumnCount())
                            jTable1.setValueAt(value.trim(), startRow + i,
                                    startCol + j);
                        System.out.println("Putting " + value + "atrow="
                                + startRow + i + "column=" + startCol + j);
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
