/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2007/02/20 12:27:07
!  AUTHOR(S): KOGA, Junichiro
!  File : HostSelectorTable.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.ssh.hosts;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import org.apache.log4j.Logger;

public class HostSelectorTable extends JTable implements HostSelector {
    private Logger logger = Logger.getLogger(HostSelectorTable.class.getName());

    private HostList list;

    public HostSelectorTable() {
        super();
        list = HostList.getHostList();
        init();
    }

    private void init() {
        setPreferredScrollableViewportSize(new Dimension(250, 10));
        setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        DefaultTableModel model = new TableMod();
        model.addColumn("hostname");
        model.addColumn("default");
        model.addTableModelListener(new Listener());
        // getSelectionModel().addListSelectionListener(new ListSelectLis());
        setModel(model);

        JCheckBox cb = new JCheckBox();
        DefaultCellEditor dce = new DefaultCellEditor(cb);
        getColumn("default").setCellEditor(dce);

        JTextField tf = new JTextField("");
        tf.setEditable(false);
        DefaultCellEditor dcet = new DefaultCellEditor(tf);
        getColumn("hostname").setCellEditor(dcet);

        for (int i = 0; i < list.size(); i++) {
            HostInfo info = list.getHostInfo(i);
            Object[] obj = { info.getName(),
                    new Boolean(info.getBooleanProperty("default")) };
            ((DefaultTableModel) getModel()).addRow(obj);
        }
    }

    public HostList getListofHosts() {
        // TODO Auto-generated method stub
        return this.list;
    }

    public HostInfo getSelectedHost() {
        int i = getSelectedRow();
        if (i >= 0)
            return list.getHostInfo(i);
        return list.getDefaultHost();
    }

    public int getSelectedIndex() {
        // TODO Auto-generated method stub
        return getSelectedRow();
    }

    public void recreate() {
        removeAll();
        init();
    }

    public void addHost(HostInfo hostInfo) {
        ((DefaultTableModel) getModel()).addRow(new Object[] {
                hostInfo.getName(), new Boolean(false) });
        list.add(hostInfo);
    }

    private static HostSelectorTable ta;

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame();
        frame.setSize(200, 100);
        JScrollPane scr = new JScrollPane();
        ta = new HostSelectorTable();
        ta.setPreferredScrollableViewportSize(new Dimension(200, 70));
        scr.getViewport().add(ta);
        JButton btn = new JButton("add");
        JPanel pp = new JPanel();
        pp.add(btn);
        pp.add(scr);
        frame.getContentPane().add(pp);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                ta.addHost(new HostInfo("foobar"));
            }
        });
    }

    private int getDefIndex() {
        for (int i = 0; i < getRowCount(); i++) {
            Object b = getValueAt(i, 1);
            if (b instanceof Boolean && ((Boolean) b).booleanValue())
                return i;
        }
        return -1;
    }

    class TableMod extends DefaultTableModel {
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }
    }

    class ListSelectLis implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent arg0) {
            // TODO Auto-generated method stub
            int column = getSelectedColumn();
            if (column != 1)
                return;

            int row = getSelectedRow();

            TableModelListener[] lists = ((DefaultTableModel) getModel())
                    .getTableModelListeners();
            for (int i = 0; i < lists.length; i++)
                ((DefaultTableModel) getModel())
                        .removeTableModelListener(lists[i]);
            for (int i = 0; i < getRowCount(); i++) {
                setValueAt(new Boolean(false), i, 1);
            }
            repaint();
            revalidate();
            setValueAt(new Boolean(true), row, 1);
            for (int i = 0; i < lists.length; i++) {
                ((DefaultTableModel) getModel())
                        .addTableModelListener(lists[i]);
            }
        }

    }

    class Listener implements TableModelListener {
        public void tableChanged(TableModelEvent e) {
            // TODO Auto-generated method stub
            int column = e.getColumn();
            if (column != 1)
                return;

            int row = e.getFirstRow();
            int larow = e.getLastRow();
            int defind = getDefIndex();

            TableModelListener[] lists = ((DefaultTableModel) getModel())
                    .getTableModelListeners();
            for (int i = 0; i < lists.length; i++)
                ((DefaultTableModel) getModel())
                        .removeTableModelListener(lists[i]);
            for (int i = 0; i < getRowCount(); i++) {
                if (i != row) {
                    setValueAt(new Boolean(false), i, 1);
                    list.getHostInfo(i).setProperty("default", "false");
                }
            }
            setValueAt(new Boolean(true), row, 1);
            list.getHostInfo(row).setProperty("default", "true");

            repaint();
            revalidate();
            for (int i = 0; i < lists.length; i++) {
                ((DefaultTableModel) getModel())
                        .addTableModelListener(lists[i]);
            }
        }

    }

    public void deleteSelectedHost() {
        // TODO Auto-generated method stub
        int ind = getSelectedRow();
        list.remove(ind);
        ((DefaultTableModel) getModel()).removeRow(ind);
    }

}
