/***************************************************************************
 *   Copyright (C) 2009 by Paul Lutus                                      *
 *   lutusp@arachnoid.com                                                  *
 *                                                                         *
 *   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 2 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, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tankcalc;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.io.*;
import javax.swing.*;

/**
 *
 * @author lutusp
 */
final public class CopyPasteTankDescription {

    TankCalc parent;
    Object[] controlList;

    public CopyPasteTankDescription(TankCalc p) {
        parent = p;
        controlList = new Object[]{
                    parent.tankOrientationComboBox,
                    parent.sensorOrientationComboBox,
                    parent.residVolumeTextField,
                    parent.tankAngleTextField,
                    parent.g_LTextField,
                    parent.g_RTextField,
                    parent.sensorXTextField,
                    parent.sensorYTextField,
                    parent.sensorZTextField,
                    parent.leftCapComboBox,
                    parent.g_rLTextField,
                    parent.rightCapComboBox,
                    parent.g_rRTextField,
                    parent.inputUnitsComboBox,
                    parent.outputUnitsComboBox,
                    parent.tableHeightStepSizeTextField,
                    parent.tableVolumeStepSizeTextField,
                    parent.decimalPlacesComboBox,
                    parent.tableTitleTextField,
                    parent.wallThicknessTextField,
                    parent.wallDensityTextField,
                    parent.contentDensityTextField,
                    parent.weightUnitsComboBox,
                    parent.leftCapCheckBox,
                    parent.cylinderCheckBox,
                    parent.rightCapCheckBox,
                    parent.sensorCheckBox,
                    parent.lineThicknessComboBox,
                    parent.anaglyphCheckBox,
                    parent.xLinesComboBox,
                    parent.yLinesComboBox,
                    parent.inverseCheckBox
                    
                };
    }

    void setClipboardContents(String s) {
        StringSelection stringSelection = new StringSelection(s);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, parent);
    }

    String getClipboardContents() {
        String s = null;
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable content = clipboard.getContents(parent);
        if (content != null) {
            try {
                s = (String) content.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e) {
                //System.out.println("getClipboardContents: " + e);
            }
        }
        return s;
    }

    public void copyTankDescription() {
        StringBuilder sb = new StringBuilder();
        Object comp;
        String name;
        for (int i = 0; i < controlList.length; i++) {
            String value = null;
            comp = controlList[i];
            name = comp.getClass().getSimpleName();
            if (name.equals("JComboBox")) {
                value = "" + ((JComboBox) comp).getSelectedIndex();
            } else if (name.equals("JCheckBox")) {
                value = ((JCheckBox) comp).isSelected() ? "1" : "0";
            } else if (name.equals("JTextField")) {
                value = (String) ((JTextField) comp).getText();
                value = value.replaceAll("\\|", "@@");
            } else if (name.equals("MutableDouble")) {
                value = String.format("%.4f", ((MutableDouble) comp).v);
            } else {
                System.out.println("cannot decode control " + name);
            }
            if (value != null) {
                if (i > 0) {
                    sb.append("|");
                }
                sb.append(value);
            }
        }
        setClipboardContents(sb.toString());
    }

    public boolean pasteTankDescription(String data) {
        boolean success = true;
        try {
            if (data != null && data.length() > 8) {
                success = false;
                data = testForFile(data);
                data = data.replaceFirst("^[\\s|\"|']*(.*?)[\\s|\"|']*$", "$1");
                data = data.replaceAll("(\n|\r|\t)", "");
                String[] array = data.split("\\|");
                // try to detect non-tank clipboard contents in a tolerant way
                if (array != null && array.length >= controlList.length / 2) {
                    Object comp;
                    String name;
                    String value;
                    // try for a degree of robustness against future changes
                    for (int i = 0; i < controlList.length && i < array.length; i++) {
                        value = array[i];
                        comp = controlList[i];
                        name = comp.getClass().getSimpleName();
                        if (name.equals("JComboBox")) {
                            ((JComboBox) comp).setSelectedIndex(Integer.parseInt(value));
                        } else if (name.equals("JCheckBox")) {
                            ((JCheckBox) comp).setSelected(value.equals("1"));
                        } else if (name.equals("JTextField")) {
                            value = value.replaceAll("@@", "|");
                            ((JTextField) comp).setText(value);
                        } else if (name.equals("MutableDouble")) {
                            ((MutableDouble) comp).v = parent.getDouble(value);
                        }
                    }
                    // if we got here, things must have gone well
                    success = true;
                    parent.setModeAndLabels();
                }
            }
        } catch (Exception e) {
            //System.out.println("copyTankDescription: " + e);
            }
        return success;
    }

    public void showError(String source) {
                parent.beep();
                JOptionPane.showMessageDialog(parent, "Unable to acquire tank description from " + source + ".", "Description Parse Error", JOptionPane.INFORMATION_MESSAGE);

    }

    public void pasteTankDescriptionFromClipboard() {
        parent.beep();
        int response = JOptionPane.showConfirmDialog(parent, "Okay to overwrite existing tank description?", "Paste new tank description", JOptionPane.OK_CANCEL_OPTION);
        if (response == JOptionPane.OK_OPTION) {
            boolean success = pasteTankDescription(getClipboardContents());
            if (!success) {
                showError("clipboard");
            }
        }
    }

    String testForFile(String data) {
        File f = new File(data);
        if (f.exists()) {
            StringBuilder sb = new StringBuilder();
            try {
                BufferedReader br = new BufferedReader(new FileReader(f));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                br.close();
                data = sb.toString();
            } catch (Exception e) {
                //System.out.println(e);
            }
        }
        // returns either file contents or original string
        return data;
    }
}