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

package cz.karry.dop.nbmodule.dbg.ui;

import cz.karry.dop.memory.Memory;
import cz.karry.dop.nbmodule.Utils;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
//import org.openide.util.Utilities;

/**
 * Top component which displays something.
 */
public final class DopDbgMemViewTopComponent extends TopComponent implements TableModelListener, cz.karry.dop.memory.MemoryChangeListener{

    private static DopDbgMemViewTopComponent instance;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";

    private static final String PREFERRED_ID = "DopDbgMemViewTopComponent";
    private DefaultTableModel dataModel;
    private Memory memory;

    private DopDbgMemViewTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(DopDbgMemViewTopComponent.class, "CTL_DopDbgMemViewTopComponent"));
        setToolTipText(NbBundle.getMessage(DopDbgMemViewTopComponent.class, "HINT_DopDbgMemViewTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
    }

    public void assignMemory(Memory memory) {
        this.memory = memory;
        memory.addChangeLisener((cz.karry.dop.memory.MemoryChangeListener)this);
        int[] data = memory.getData();
        dataModel = new javax.swing.table.DefaultTableModel(
                new String [] { "address", "value" }, 
                data.length){
            
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Object.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

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

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }            
        };
        
        dataTable.setModel( dataModel );
        for (int i=0; i< data.length; i++){
            dataModel.setValueAt("0x"+Utils.intToHex(i, 2), i, 0);
            dataModel.setValueAt(Utils.intToHex(data[i], 2), i, 1);
        }
        dataModel.addTableModelListener(this);
    }
    

    public void tableChanged(TableModelEvent e) {
        if (e.getColumn() == 1){
            int value = 0;
            String str;
            int min = Math.min(e.getFirstRow(), e.getLastRow());
            int max = Math.max(e.getFirstRow(), e.getLastRow());
            for (int i=min ; i<=max; i++){
                str = String.valueOf( dataTable.getValueAt(i, 1) );
                try {
                    value = Utils.hexToInt(str);
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, ex.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);   
                    dataTable.setValueAt( Utils.intToHex( memory.getValue(i), 2 ), i, 1);
                    break;
                }
                if (value > 0xff){
                    JOptionPane.showMessageDialog(this, "Value \""+str+"\" is greater than 0xFF!","Error",JOptionPane.ERROR_MESSAGE);
                    dataTable.setValueAt( Utils.intToHex( memory.getValue(i),2 ), i, 1);
                    break;
                }
                memory.setValue(i, value);
            }
        }
    }    
    
    public void memoryChangePerformed(int address, int value) {
        dataModel.setValueAt("0x"+Utils.intToHex(address, 2), address, 0);
        dataModel.setValueAt(Utils.intToHex(value, 2), address, 1);        
    }    

    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        dataTable = new javax.swing.JTable();

        dataTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "address", "value"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

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

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(dataTable);
        dataTable.getColumnModel().getColumn(0).setHeaderValue(org.openide.util.NbBundle.getMessage(DopDbgMemViewTopComponent.class, "DopDbgMemViewTopComponent.dataTable.columnModel.title0")); // NOI18N
        dataTable.getColumnModel().getColumn(1).setHeaderValue(org.openide.util.NbBundle.getMessage(DopDbgMemViewTopComponent.class, "DopDbgMemViewTopComponent.dataTable.columnModel.title2")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 177, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable dataTable;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized DopDbgMemViewTopComponent getDefault() {
        if (instance == null) {
            instance = new DopDbgMemViewTopComponent();
        }
        return instance;
    }

    /**
     * Obtain the DopDbgMemViewTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized DopDbgMemViewTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            Logger.getLogger(DopDbgMemViewTopComponent.class.getName()).warning(
                    "Cannot find " + PREFERRED_ID + " component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof DopDbgMemViewTopComponent) {
            return (DopDbgMemViewTopComponent) win;
        }
        Logger.getLogger(DopDbgMemViewTopComponent.class.getName()).warning(
                "There seem to be multiple components with the '" + PREFERRED_ID +
                "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }

    @Override
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }

    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    /** replaces this in object stream */
    @Override
    public Object writeReplace() {
        return new ResolvableHelper();
    }

    @Override
    protected String preferredID() {
        return PREFERRED_ID;
    }

    final static class ResolvableHelper implements Serializable {

        private static final long serialVersionUID = 1L;

        public Object readResolve() {
            return DopDbgMemViewTopComponent.getDefault();
        }
    }



}
