/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2006/06/05, 11:08
!  AUTHOR(S): KOGA, Junichiro
!  File : FileTransferInfoEditorPanel.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.file;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import org.apache.log4j.Logger;

import ciss.phase_viewer.common.InputPanel;
import ciss.phase_viewer.mainpanel.InternalFrameChase;

/**
 * ファイル転送情報の編集をすることができるGUI.
 * 
 * @author
 */
public class FileTransferInfoEditorPanel extends InternalFrameChase {
    private Logger logger = Logger.getLogger(FileTransferInfoEditorPanel.class
            .getName());

    private ChaseFileManager fileManager;

    /**
     * ファイルを管理しているオブジェクトを引数にとる.
     * 
     * @param fileManager
     *            ファイル情報を持っているオブジェクト.
     */
    public FileTransferInfoEditorPanel(ChaseFileManager fileManager) {
        super("edit file-transfer info", true, true, true, true, new Dimension(
                700, 420));
        this.fileManager = fileManager;
        init();
    }

    private void init() {
        Container cont = getContentPane();
        // cont.setLayout(new BoxLayout(cont,BoxLayout.Y_AXIS));
        cont.setLayout(new BorderLayout());
        cont.add(createPathViewers(), BorderLayout.NORTH);
        JPanel paa = createTable();
        cont.add(paa, BorderLayout.CENTER);
        cont.add(createButtons(), BorderLayout.SOUTH);
    }

    private JPanel createPathViewers() {
        logger.debug("at createPathViewers()");
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

        InputPanel target = new InputPanel("target dir for "
                + fileManager.getHostInfo().getName(), 0, 10);
        // InputPanel target = new InputPanel("target dir",0,10);
        target.setValue(fileManager.getProjectInfo().getTargetDirectory());
        target.getTextField().setEditable(false);
        panel.add(target);

        return panel;
    }

    private DefaultTableModel tableModel;
    private FileTransferSchemeTable table;
    private ChaseFileInfoSpec[] specs;
    private ChaseFile[] chaseFiles;

    private JPanel createTable() {
        logger.debug("at createtable");
        JPanel panel = new JPanel();
        chaseFiles = fileManager.getFiles();
        if (chaseFiles == null || chaseFiles.length == 0) {
            logger.error("invalid ChaseFile's");
            return new JPanel();
        }

        ChaseFileInfoSpec[] tmpspec = fileManager.getFileInfoSpecs();
        Vector vec = new Vector();
        for (int i = 0; i < tmpspec.length; i++) {
            if (!tmpspec[i].getEditor().equals("null")) {
                vec.addElement(tmpspec[i]);
            }
        }
        specs = new ChaseFileInfoSpec[vec.size()];
        vec.copyInto(specs);

        int numfiles = chaseFiles.length;

        String[] colnames = new String[specs.length];
        for (int i = 0; i < specs.length; i++) {
            colnames[i] = specs[i].getName();
            logger.debug("column name: " + colnames[i]);
        }

        tableModel = new FileTransferSchemeTableModel(colnames, numfiles);
        table = new FileTransferSchemeTable(tableModel, specs);

        for (int i = 0; i < chaseFiles.length; i++) {
            for (int j = 0; j < table.getColumnCount(); j++) {
                String cname = table.getColumnName(j);
                Object val = chaseFiles[i].getValue(cname);
                if (val != null) {
                    table.setValueAt(val, i, j);
                }
            }
        }

        JPanel ptab = new JPanel();
        ptab.setLayout(new BoxLayout(ptab, BoxLayout.Y_AXIS));
        ptab.add(table.getTableHeader());
        ptab.add(table);
        JScrollPane scrpane = new JScrollPane(ptab);
        scrpane.setPreferredSize(new Dimension(650, 300));
        // panel.add(ptab);
        panel.add(scrpane);
        return panel;
    }

    private JPanel createButtons() {
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(1, 2));
        JButton btnsave = new JButton("save to disk");
        JButton btnclose = new JButton("close");

        btnsave.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                saveToDisk();
            }
        });

        btnclose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        panel.add(btnsave);
        panel.add(btnclose);

        return panel;
    }

    private void saveToDisk() {
        logger.debug("saving file info...");
        if (specs == null || specs.length == 0) {
            logger.info("nothing to save.");
            return;
        }
        if (table.getRowCount() != chaseFiles.length) {
            logger.error("rowCount and filenum inconsistent !!");
            return;
        }
        for (int i = 0; i < table.getRowCount(); i++) {
            for (int j = 0; j < table.getColumnCount(); j++) {
                String ident = table.getColumnName(j);
                logger.debug("saving " + ident + " for: "
                        + chaseFiles[i].getIdentifier().getValue());
                Object obj = table.getValueAt(i, j);
                chaseFiles[i].update(ident, table.getValueAt(i, j).toString());
            }
        }
        fileManager.save();
    }
}

class FileTransferSchemeTable extends JTable {
    private Logger logger = Logger.getLogger(FileTransferSchemeTable.class
            .getName());
    private DefaultTableModel tableModel;
    private ChaseFileInfoSpec[] spec;

    protected FileTransferSchemeTable(DefaultTableModel tableModel,
            ChaseFileInfoSpec[] spec) {
        super(tableModel);
        this.tableModel = tableModel;
        this.spec = spec;
        this.setSelectionForeground(Color.white);
        init();
    }

    private void init() {
        for (int i = 0; i < spec.length; i++) {
            ChaseFileInfoSpec cfspec = spec[i];
            if (cfspec.getEditor().equals(ChaseFileInfoSpec.EDITOR_TEXTFIELD)) {
                JTextField textField = new JTextField(cfspec.getDefaultValue());
                textField.setEditable(cfspec.isEditable());
                this.getColumnModel().getColumn(i)
                        .setCellEditor(new DefaultCellEditor(textField));
                for (int j = 0; j < getRowCount(); j++) {
                    setValueAt(cfspec.getDefaultValue(), j, i);
                }
            } else if (cfspec.getEditor()
                    .equals(ChaseFileInfoSpec.EDITOR_COMBO)) {
                JComboBox combo = new JComboBox(cfspec.getChoices());
                // combo.setEditable(tscheme.isEditable());
                combo.setSelectedItem(cfspec.getDefaultValue());
                this.getColumnModel().getColumn(i)
                        .setCellEditor(new DefaultCellEditor(combo));
                for (int j = 0; j < getRowCount(); j++) {
                    setValueAt(cfspec.getDefaultValue(), j, i);
                }
            } else if (cfspec.getEditor().equals(
                    ChaseFileInfoSpec.EDITOR_CHECKBOX)) {
                JCheckBox checkBox = new JCheckBox();
                checkBox.setEnabled(cfspec.isEditable());
                boolean val = new Boolean(cfspec.getDefaultValue())
                        .booleanValue();
                checkBox.setSelected(val);
                this.getColumnModel().getColumn(i)
                        .setCellEditor(new DefaultCellEditor(checkBox));
                for (int j = 0; j < getRowCount(); j++) {
                    setValueAt(new Boolean(cfspec.getDefaultValue()), j, i);
                }
            }
        }
    }

}

class FileTransferSchemeTableModel extends DefaultTableModel {
    protected FileTransferSchemeTableModel() {
        super();
    }

    protected FileTransferSchemeTableModel(Object[] objs, int rowcount) {
        super(objs, rowcount);
    }

    public Class getColumnClass(int c) {
        Object obj = getValueAt(0, c);
        if (obj != null) {
            return obj.getClass();
        }
        return super.getColumnClass(c);
    }

}
