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

/*
 * ToolMaterialMasterPanel.java
 *
 * Created on 2009/08/18, 19:16:40
 */
package open.dolphin.client.editor.toolmaterial;

import open.dolphin.order.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.GregorianCalendar;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;

import open.dolphin.client.MasterRenderer;
import open.dolphin.infomodel.MasterItem;
import open.dolphin.infomodel.ToolMaterialEntry;
import open.dolphin.log.LogWriter;
import open.dolphin.table.ObjectTableModel;

/**
 *　器材マスタ　MEMO:画面
 * @author
 */
public class ToolMaterialMasterPanel extends AbstractMasterPanel {

    private static final long serialVersionUID = 8468185276474656951L;
    private static final String[] toolMaterialColumns = {"コード", "名  称", "カ ナ", "単位", "点数識別", "点数/金額", "開始年月日", "終了年月日"}; //GlobalVariables.getStringArray("masterSearch.toolMaterial.columnNames");
    private static final String[] toolMaterialCostFlags = {"廃", "金", "都", "", "", "%加", "", "", "", "乗"}; //GlobalVariables.getStringArray("masterSearch.toolMaterial.costFlags");
//    private static final String[] sortButtonNames = GlobalVariables.getStringArray("masterSearch.toolMaterial.sortButtonNames");
    private static final String[] sortColumnNames = {"srycd", "name", "kananame", "taniname", "tensikibetu", "ten", "yukostymd", "yukoedymd"}; //GlobalVariables.getStringArray("masterSearch.toolMaterial.sortColumnNames");

    /** Creates new form ToolMaterialMasterPanel
     * @param master 
     */
    public ToolMaterialMasterPanel(String master) {
        super(master);
    }

    /**
     *
     */
    @Override
    protected void initialize() {

        initComponents();

        // Table Model を生成する
        tableModel = new ObjectTableModel(toolMaterialColumns, START_NUM_ROWS) {

            @Override
            public Class getColumnClass(int col) {
                return ToolMaterialEntry.class;
            }
        };
        table.setModel(tableModel);

        JTableHeader header = table.getTableHeader();
        header.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e) {
                doSort(e);
            }
        });

        // 列幅を設定する
        TableColumn column = null;
        int[] width = new int[]{50, 200, 200, 40, 30, 50, 50};
        int len = width.length;
        for (int i = 0; i < len; i++) {
            column = table.getColumnModel().getColumn(i);
            column.setPreferredWidth(width[i]);
        }

        // カスタムレンダラー登録
        ToolMaterialMasterRenderer masterTableRenderer = new ToolMaterialMasterRenderer();
        masterTableRenderer.setBeforStartColor(masterColors[0]);
        masterTableRenderer.setInUseColor(masterColors[1]);
        masterTableRenderer.setAfterEndColor(masterColors[2]);
        masterTableRenderer.setCostFlag(toolMaterialCostFlags);
        table.setDefaultRenderer(ToolMaterialEntry.class, masterTableRenderer);

        key.setLayout(new FlowLayout(FlowLayout.LEFT, 7, 5));
        key.add(findLabel);
        key.add(new JLabel(masterTabNames[3] + ":"));
        key.add(keywordField);
        key.add(isForwordCheckBox);
        key.setBorder(BorderFactory.createTitledBorder(keywordBorderTitle));

        top.setLayout(new BoxLayout(top, BoxLayout.X_AXIS));
        top.add(Box.createHorizontalGlue());

        this.setLayout(new BorderLayout(0, 11));
        this.add(top, BorderLayout.NORTH);
        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() {

        scroller = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        top = new javax.swing.JPanel();
        key = new javax.swing.JPanel();

        scroller.setName("scroller"); // NOI18N

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        table.setName("table"); // NOI18N
        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableMouseClicked(evt);
            }
        });
        scroller.setViewportView(table);

        top.setName("top"); // NOI18N

        key.setName("key"); // NOI18N

        javax.swing.GroupLayout keyLayout = new javax.swing.GroupLayout(key);
        key.setLayout(keyLayout);
        keyLayout.setHorizontalGroup(
            keyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 330, Short.MAX_VALUE)
        );
        keyLayout.setVerticalGroup(
            keyLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 45, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout topLayout = new javax.swing.GroupLayout(top);
        top.setLayout(topLayout);
        topLayout.setHorizontalGroup(
            topLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(topLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(key, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(114, Short.MAX_VALUE))
        );
        topLayout.setVerticalGroup(
            topLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(topLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(key, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(top, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(scroller, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(top, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scroller, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    /**
     *
     * @param evt
     */
    private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
        if (evt.getClickCount() == 2) {
            int row = table.getSelectedRow();
            ToolMaterialEntry original = (ToolMaterialEntry) tableModel.getObject(row);
            //   if (original != null && original.isInUse()) {
            if (original != null && (original.useState(new GregorianCalendar()) != 2)) {//isInUse()は日付がNULL、Emptyで真を返してしまうので
                MasterItem mainItem = new MasterItem(1, original);
                mainItem.setUnit(original.getUnit());
                setSelectedItem(mainItem);
                ToolMaterialEntry required = original.getRequiredToolMaterial(); //必要な追加機材があれば追加
                if (required != null) {
                    MasterItem requiredItem = new MasterItem(1, required);
                    requiredItem.setUnit(required.getUnit());
                    setSelectedItem(requiredItem);
                }
            }
        }
    }//GEN-LAST:event_tableMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel key;
    private javax.swing.JScrollPane scroller;
    private javax.swing.JTable table;
    private javax.swing.JPanel top;
    // End of variables declaration//GEN-END:variables

    /**
     *
     * @param e
     */
    private void doSort(MouseEvent e) {
        int viewColumn = table.getTableHeader().columnAtPoint(e.getPoint());
        int modelColumn = table.convertColumnIndexToModel(viewColumn);
        setSortBy(sortColumnNames[modelColumn]);
        String _key = keywordField.getText().trim();
        search(_key, !isForwordCheckBox.isSelected());
    }

    /**
     *
     */
    @Override
    public void clear() {
        tableModel.clear();
        keywordField.setText("");
    }

    /**
     * 器材マスタ Table のレンダラー
     */
    protected final class ToolMaterialMasterRenderer extends MasterRenderer {

        private static final long serialVersionUID = 5382872864219480731L;
        private final int CODE_COLUMN = 0;
        private final int NAME_COLUMN = 1;
        private final int KANA_COLUMN = 2;
        private final int UNIT_COLUMN = 3;
        private final int COST_FLAG_COLUMN = 4;
        private final int COST_COLUMN = 5;
        private final int START_COLUMN = 6;
        private final int END_COLUMN = 7;
        private String[] costFlags;

        /**
         *
         */
        public ToolMaterialMasterRenderer() {
        }

        /**
         *
         * @return
         */
        public String[] getCostFlag() {
            return costFlags;
        }

        /**
         *
         * @param val
         */
        public void setCostFlag(String[] val) {
            costFlags = val;
        }

        /**
         *
         * @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 c = super.getTableCellRendererComponent(
                    table,
                    value,
                    isSelected,
                    isFocused,
                    row, col);
            if (isSelected) {
                setBackground(table.getSelectionBackground());
                setForeground(table.getSelectionForeground());
            } else {

                setForeground(table.getForeground());
                setBackground(table.getBackground());
            }
            JLabel label = (JLabel) c;

            if (value != null && value instanceof ToolMaterialEntry) {

                ToolMaterialEntry entry = (ToolMaterialEntry) value;

                String startDate = entry.getStartDate();
                String endDate = entry.getEndDate();

                setColor(label, startDate, endDate);

                String tmp = null;

                switch (col) {

                    case CODE_COLUMN:
                        label.setText(entry.getCode());
                        break;

                    case NAME_COLUMN:
                        label.setText(entry.getName());
                        break;

                    case KANA_COLUMN:
                        label.setText(entry.getKana());
                        break;

                    case UNIT_COLUMN:
                        label.setText(entry.getUnit());
                        break;

                    case COST_FLAG_COLUMN:
                        tmp = entry.getCostFlag();
                        if (tmp != null) {
                            try {
                                int index = Integer.parseInt(tmp);
                                label.setText(costFlags[index]);
                            } catch (Exception e) {
                                label.setText("");
                                LogWriter.error(this.getClass(), "", e);
                            }
                        } else {
                            label.setText("");
                        }
                        break;

                    case COST_COLUMN:
                        label.setText(entry.getCost());
                        break;

                    case START_COLUMN:
                        if (startDate.startsWith("0")) {
                            label.setText("");
                        } else {
                            label.setText(startDate);
                        }
                        break;

                    case END_COLUMN:
                        if (endDate.startsWith("9")) {
                            label.setText("");
                        } else {
                            label.setText(endDate);
                        }
                        break;
                    default: LogWriter.fatal(getClass(), "case default");
                }
            } else {
                label.setBackground(Color.white);
                label.setText(value == null ? "" : value.toString());
            }
            return c;
        }
    }
}
