/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jpnCondition.java
 *
 * Created on May 1, 2010, 10:37:53 PM
 */

package uce.ui.components;

import java.awt.Component;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.swing.AbstractCellEditor;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

/**
 *
 * @author chepa
 */
public class jpnCondition extends javax.swing.JPanel {

	XMLGregorianCalendar m_FormatCalendar;

	private enum ConditionType {

		WHEN_DATE_TIME, AFTER_TIME, WHEN_TIME, ONT_VALUE_CONDITION;

		@Override
		public String toString() {
			if (this == WHEN_DATE_TIME) {
				return "When DateTime = <SpecificValue>";
			}
			if (this == AFTER_TIME) {
				return "After time = <SpecificValue>";
			}
			if (this == WHEN_TIME) {
				return "When Time = <SpecificValue>";
			}
			if (this == ONT_VALUE_CONDITION) {
				return "Ontology Value Condition";
			}
			return super.toString();
		}
	}

	public static class MyTime {

		private int m_Hr, m_Min, m_Sec;

		public MyTime(int hr, int min, int sec) {
			m_Hr = hr;
			m_Min = min;
			m_Sec = sec;
		}

		@Override
		public String toString() {
			return String.format("%d Hour(s), %d Minute(s), %d Second(s)", m_Hr, m_Min, m_Sec);
		}

		public int getHours() {
			return m_Hr;
		}

		public int getMins() {
			return m_Min;
		}

		public int getSecs() {
			return m_Sec;
		}
	}

	private class DateTimeChooserEditorRenderer {

		private pnlDateTimePicker m_pnlDateTimePicker;

		private class DateTimeChooser extends AbstractCellEditor implements TableCellEditor {

			private JTable m_Table;
			private int m_Row, m_RowHeight;

			public Object getCellEditorValue() {
				m_Table.setRowHeight(m_Row, m_RowHeight);
				return m_pnlDateTimePicker.getDateTime();
			}

			public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
				if (m_pnlDateTimePicker == null) {
					m_pnlDateTimePicker = new pnlDateTimePicker();
				}
				Object obj = table.getValueAt(row, column);
				if (obj != null && obj instanceof Calendar) {
					m_pnlDateTimePicker.setDateTime((Calendar) obj);
				}
				m_Row = row;
				m_RowHeight = table.getRowHeight(row);
				m_Table = table;
				table.setRowHeight(row, m_pnlDateTimePicker.getPreferredSize().height);
				return m_pnlDateTimePicker;
			}
		}
		private DateTimeChooser m_editor = new DateTimeChooser();

		public TableCellEditor getEditor() {
			return m_editor;
		}
		private DateTimeCellRenderer m_renderer = new DateTimeCellRenderer();

		public TableCellRenderer getRenderer() {
			return m_renderer;
		}

		private class DateTimeCellRenderer extends DefaultTableCellRenderer {

			@Override
			public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
				Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
				if (comp instanceof JLabel && value instanceof Calendar) {
					Calendar cal = (Calendar) value;
					GregorianCalendar g_cal = new GregorianCalendar();
					g_cal.setTime(cal.getTime());
					try {
						m_FormatCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(g_cal);
						String strRep = String.format("WHEN_DATE_TIME=%s", m_FormatCalendar.toString());
						((JLabel) comp).setText(strRep);
					} catch (DatatypeConfigurationException ex) {
						ex.printStackTrace();
					}
				}
				return comp;
			}
		}
	}

	private class TimeChooser extends AbstractCellEditor implements TableCellEditor {

		private pnlTimePicker m_TimePicker;
		private JTable m_Table;
		private int m_Row, m_RowHeight;

		public Object getCellEditorValue() {
			m_Table.setRowHeight(m_Row, m_RowHeight);
			return m_TimePicker.getTime();
		}

		public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
			if (m_TimePicker == null) {
				m_TimePicker = new pnlTimePicker();
			}
			Object obj = table.getValueAt(row, column);
			if (obj != null && obj instanceof MyTime) {
				m_TimePicker.setTime((MyTime) obj);
			}
			m_Row = row;
			m_RowHeight = table.getRowHeight(row);
			m_Table = table;
			table.setRowHeight(row, m_TimePicker.getPreferredSize().height);
			return m_TimePicker;
		}
	}

	private class ConditionCellEditorRenderer {

		private JComboBox m_cmbCondType;

		{
			m_cmbCondType = new JComboBox(new DefaultComboBoxModel(ConditionType.values()));
		}
		private ConditionCellEditor m_editor = new ConditionCellEditor();

		public TableCellEditor getEditor() {
			return m_editor;
		}

		private class ConditionCellEditor extends AbstractCellEditor implements TableCellEditor {

			private Object m_PrevValue;
			private JTable m_Table;
			private int m_Row;

			{
				m_cmbCondType.addItemListener(new ItemListener() {

					public void itemStateChanged(ItemEvent e) {
						Object value = e.getItem();
						if (!value.equals(m_PrevValue)) {
							m_Table.setValueAt(null, m_Row, 1);
						}
					}
				});
			}

			public Object getCellEditorValue() {
				return m_cmbCondType.getSelectedItem();
			}

			public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
				m_PrevValue = value;
				m_Table = table;
				m_Row = row;
				return m_cmbCondType;
			}
		}
		private ConditionCellRenderer m_renderer = new ConditionCellRenderer();

		public TableCellRenderer getRenderer() {
			return m_renderer;
		}

		private class ConditionCellRenderer extends DefaultTableCellRenderer {

			@Override
			public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
				return m_cmbCondType;
			}
		}
	}

	/** Creates new form jpnCondition */
	public jpnCondition() {
		initComponents();
	}

	public jpnCondition(String title) {
		this();
		jscrCond.setBorder(new TitledBorder(title));
		jtbCourseCond.addComponentListener(new ComponentAdapter() {

			@Override
			public void componentResized(ComponentEvent e) {
				super.componentResized(e);
				int width = jtbCourseCond.getWidth();
				double[] aRatio = new double[]{.1, .6, .3};
				for (int i = 0; i < aRatio.length; i++) {
					jtbCourseCond.getColumnModel().getColumn(i).setMinWidth((int) (width * aRatio[i]));
					jtbCourseCond.getColumnModel().getColumn(i).setMaxWidth((int) (width * aRatio[i]));
					jtbCourseCond.getColumnModel().getColumn(i).setWidth((int) (width * aRatio[i]));
				}
			}
		});
	}

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jscrCond = new javax.swing.JScrollPane();
        jtbCourseCond = new javax.swing.JTable(){
            private ConditionCellEditorRenderer edtRend = new ConditionCellEditorRenderer();
            private TimeChooser timeChooser = new TimeChooser();
            private DateTimeChooserEditorRenderer dtEdtRen = new DateTimeChooserEditorRenderer();
            public TableCellRenderer getCellRenderer(int row, int column) {
                if (column == 2) {
                    return edtRend.getRenderer();
                }
                if(column==1){
                    ConditionType cndType = (ConditionType) this.getValueAt(row, 2);
                    if (cndType == ConditionType.WHEN_DATE_TIME)
                    return dtEdtRen.getRenderer();
                }
                return super.getCellRenderer(row, column);
            }
            public TableCellEditor getCellEditor(int row, int column) {
                if (column == 2) {
                    return edtRend.getEditor();
                }
                if(column==1){
                    ConditionType cndType = (ConditionType) this.getValueAt(row, 2);
                    if (cndType == ConditionType.AFTER_TIME || cndType == ConditionType.WHEN_TIME)
                    return timeChooser;
                    if (cndType == ConditionType.WHEN_DATE_TIME)
                    return dtEdtRen.getEditor();
                    return new DefaultCellEditor(new JTextField());
                }
                return super.getCellEditor(row, column);
            }
        };

        jtbCourseCond.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null}
            },
            new String [] {
                "No.", "Condition", "Type"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtbCourseCond.setRowSelectionAllowed(false);
        jtbCourseCond.getTableHeader().setReorderingAllowed(false);
        jscrCond.setViewportView(jtbCourseCond);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 427, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jscrCond, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jscrCond, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jscrCond;
    private javax.swing.JTable jtbCourseCond;
    // End of variables declaration//GEN-END:variables

}
