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

/*
 * ImageHistoryPanel.java
 *
 * Created on 2010/03/19, 16:03:32
 */
package open.dolphin.client.caremapdocument;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;

import open.dolphin.client.IChartDocument;
import open.dolphin.client.ImageEntry;
import open.dolphin.project.GlobalSettings;
import open.dolphin.delegater.remote.RemoteDocumentDelegater;
import open.dolphin.dto.ImageSearchSpec;
import open.dolphin.helper.DBTask;
import open.dolphin.infomodel.SchemaModel;

/**
 *　画像履歴　MEMO:画面　リスナー
 * @author 
 */
public class ImageHistoryPanel extends javax.swing.JPanel implements PropertyChangeListener {

    private String pid;
    private IChartDocument myParent;
    private ImageTableModel tModel;
    private JTable table;
    private int columnCount = 5;
    private int imageWidth = 132;
    private int imageHeight = 132;
    private javax.swing.Timer taskTimer;//MEMO: unused?

    /**
     * Creates new form ImageHistoryPanel
     */
    public ImageHistoryPanel() {
        super();
        initComponents();

        setLayout(new BorderLayout());

        tModel = new ImageTableModel();
        table = new JTable(tModel);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        table.setCellSelectionEnabled(true);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        TableColumn column = null;
        for (int i = 0; i < columnCount; i++) {
            column = table.getColumnModel().getColumn(i);
            column.setPreferredWidth(imageWidth);
        }
        table.setRowHeight(imageHeight + 20);

        ImageRenderer imageRenderer = new ImageRenderer();
        imageRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        table.setDefaultRenderer(java.lang.Object.class, imageRenderer);

        table.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() != 2) {
                    return;
                }
                Point loc = e.getPoint();
                int row = table.rowAtPoint(loc);
                int col = table.columnAtPoint(loc);
                if (row != -1 && col != -1) {
                    openImage(row, col);
                }
            }
        });

        JScrollPane scroller = new JScrollPane(table,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scroller.getViewport().setBackground(GlobalSettings.getColors(GlobalSettings.Parts.TABLE_BACKGROUND));
        this.add(scroller, BorderLayout.CENTER);
    }

    /** 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() {

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
    /**
     *
     * @return
     */
    public String getPid() {
        return pid;
    }

    /**
     *
     * @param val
     */
    public void setPid(String val) {
        pid = val;
    }

    /**
     *
     * @param doc
     */
    public void setMyParent(IChartDocument doc) {
        myParent = doc;
    }

    /**
     *
     * @param allImages
     */
    @SuppressWarnings("unchecked")
    public void setImageList(List allImages) {

        if (allImages != null) {

            int size = allImages.size();
            List list = new ArrayList();

            for (int i = 0; i < size; i++) {
                List l = (List) allImages.get(i);
                if (l != null) {
                    for (int j = 0; j < l.size(); j++) {
                        list.add(l.get(j));
                    }
                }
            }
            tModel.setImageList(list);
        } else {
            tModel.setImageList(allImages);
        }
    }

    /**
     *
     * @param e
     */
    @Override
    public void propertyChange(PropertyChangeEvent e) {

        String prop = e.getPropertyName();
        if (prop.equals(CareMapDocumentPanel.SELECTED_DATE_PROP)) {
            String date = (String) e.getNewValue();
            findDate(date);
        }

    }

    /**
     *
     * @param date
     */
    private void findDate(String date) {
        int index = tModel.findDate(date);
        if (index != -1) {
            int row = index / columnCount;
            int col = index % columnCount;
            table.setRowSelectionInterval(row, row);
            table.setColumnSelectionInterval(col, col);
        }
    }

    /**
     *
     * @param row
     * @param col
     */
    private void openImage(int row, int col) {

        ImageEntry entry = (ImageEntry) tModel.getValueAt(row, col);
        final ImageSearchSpec spec = new ImageSearchSpec();
        spec.setCode(ImageSearchSpec.ID_SEARCH);
        spec.setId(entry.getId());
        final RemoteDocumentDelegater ddl = new RemoteDocumentDelegater();

        DBTask task = new DBTask<SchemaModel>(myParent.getParentContext()) {

            @Override
            public SchemaModel doInBackground() throws Exception {
                return ddl.getImage(spec.getId());
            }

            @Override
            public void succeeded(SchemaModel result) {
                openDialog(result);
            }
        };

        task.execute();
    }

    /**
     *
     * @param schema
     */
    private void openDialog(SchemaModel schema) {
    }

    /**
     * 　MEMO:モデル
     */
    protected class ImageTableModel extends AbstractTableModel {

        private static final long serialVersionUID = -2683619747572366737L;
        private List imageList;

        /**
         *
         * @return
         */
        @Override
        public int getColumnCount() {
            return columnCount;
        }

        /**
         *
         * @return
         */
        @Override
        public int getRowCount() {
            if (imageList == null) {
                return 0;
            }

            int size = imageList.size();
            int rowCount = size / columnCount;

            return ((size % columnCount) != 0) ? rowCount + 1 : rowCount;
        }

        /**
         *
         * @param row
         * @param col
         * @return
         */
        @Override
        public Object getValueAt(int row, int col) {
            int index = row * columnCount + col;
            if (!isValidIndex(index)) {
                return null;
            }

            ImageEntry s = (ImageEntry) imageList.get(index);
            return (Object) s;
        }

        /**
         * 
         * @param list
         */
        public void setImageList(List list) {
            if (imageList != null) {
                int last = getRowCount();
                imageList.clear();
                fireTableRowsDeleted(0, last);
            }
            imageList = list;
            int last = getRowCount();
            fireTableRowsInserted(0, last);
        }

        /**
         *
         * @param date
         * @return
         */
        private int findDate(String date) {

            int ret = -1;

            if (imageList == null) {
                return ret;
            }

            int size = imageList.size();
            for (int i = 0; i < size; i++) {
                ImageEntry entry = (ImageEntry) imageList.get(i);
                if (entry.getConfirmDate().startsWith(date)) {
                    ret = i;
                    break;
                }
            }
            return ret;
        }

        /**
         *
         * @param index
         * @return
         */
        private boolean isValidIndex(int index) {
            return (imageList == null || index < 0 || index >= imageList.size()) ? false
                    : true;
        }
    }

    /**
     * MEMO:Component
     */
    protected class ImageRenderer extends DefaultTableCellRenderer {

        private static final long serialVersionUID = -8136363583689791913L;

        /**
         *
         */
        public ImageRenderer() {
            setVerticalTextPosition(JLabel.BOTTOM);
            setHorizontalTextPosition(JLabel.CENTER);
        }

        /**
         *
         * @param table
         * @param value
         * @param isSelected
         * @param isFocused
         * @param row
         * @param col
         * @return
         */
        @Override
        public Component getTableCellRendererComponent(JTable table,
                Object value, boolean isSelected, boolean isFocused, int row,
                int col) {
            Component compo = super.getTableCellRendererComponent(table, value,
                    isSelected, isFocused, row, col);
            JLabel l = (JLabel) compo;

            if (value != null) {

                ImageEntry entry = (ImageEntry) value;
                l.setIcon(entry.getImageIcon());
                // String title = entry.getTitle();
                // if (title != null) {
                // l.setText(title);

                // } else {
                l.setText(entry.getConfirmDate().substring(0, 10));
                // }

            } else {
                l.setIcon(null);
            }
            return compo;
        }
    }
}
