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

/*
 * AreaNetWorkSettingPanel.java
 *
 * Created on 2010/03/09, 11:25:54
 */
package open.dolphin.client.settings;

import open.dolphin.project.GlobalConstants;
import open.dolphin.container.NameValuePair;
import java.awt.event.ItemEvent;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JPanel;

import open.dolphin.client.AutoRomanListener;
import open.dolphin.log.LogWriter;
import open.dolphin.project.GlobalVariables;
import open.dolphin.utils.Adapter;

/**
 *
 * @author
 */
public class AreaNetWorkSettingPanel extends javax.swing.JPanel implements IAbstractSettingPanel {

    private ProjectSettingDialog context;
    private PropertyChangeSupport boundSupport;
    protected State state = State.NONE_STATE;
    private boolean loginState;
    private String title;
    private String icon;
    private String id;
    private NameValuePair[] networkProjects;
    private NetworkModel model;
    private StateMgr stateMgr;
    private Adapter<Boolean, Boolean> adapter;

    /** Creates new form AreaNetWorkSettingPanel */
    public AreaNetWorkSettingPanel() {
        boundSupport = new PropertyChangeSupport(this);
        model = new NetworkModel();
        initComponents();

        setId("areaNetwork");
        setTitle("地域連携");
        setIcon("Globe2.png");

    }

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


        bg = new javax.swing.ButtonGroup();
        content = new javax.swing.JPanel();
        panel1 = new javax.swing.JPanel();
        joinAreaNetwork = new javax.swing.JRadioButton();
        noJoinAreaNetwork = new javax.swing.JRadioButton();
        groupPanel = new javax.swing.JPanel();
        label1 = new javax.swing.JLabel();
        areaNetworkCombo = new javax.swing.JComboBox();
        label2 = new javax.swing.JLabel();
        facilityIdField = new javax.swing.JTextField();
        label3 = new javax.swing.JLabel();
        creatorIdField = new javax.swing.JTextField();

        setLayout(new java.awt.GridLayout(1, 0));

        content.setBorder(javax.swing.BorderFactory.createTitledBorder("地域連携"));
        content.setName("content"); // NOI18N

        panel1.setName("panel1"); // NOI18N
        panel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 5));

        bg.add(joinAreaNetwork);
        joinAreaNetwork.setText("参加する");
        joinAreaNetwork.setName("joinAreaNetwork"); // NOI18N
        joinAreaNetwork.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                joinAreaNetworkActionPerformed(evt);
            }
        });
        panel1.add(joinAreaNetwork);

        bg.add(noJoinAreaNetwork);
        noJoinAreaNetwork.setText("参加しない");
        noJoinAreaNetwork.setName("noJoinAreaNetwork"); // NOI18N
        noJoinAreaNetwork.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                noJoinAreaNetworkActionPerformed(evt);
            }
        });
        panel1.add(noJoinAreaNetwork);

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

        label1.setText("プロジェクト:");
        label1.setName("label1"); // NOI18N


        areaNetworkCombo.setName("areaNetworkCombo"); // NOI18N
        areaNetworkCombo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                areaNetworkComboItemStateChanged(evt);
            }
        });

        label2.setText("連携用医療機関ID:");
        label2.setName("label2"); // NOI18N


        facilityIdField.setColumns(20);
        facilityIdField.setName("facilityIdField"); // NOI18N

        label3.setText("連携用ユーザID:");
        label3.setName("label3"); // NOI18N


        creatorIdField.setColumns(20);
        creatorIdField.setName("creatorIdField"); // NOI18N
        creatorIdField.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                creatorIdFieldPropertyChange(evt);
            }
        });

        javax.swing.GroupLayout groupPanelLayout = new javax.swing.GroupLayout(groupPanel);
        groupPanel.setLayout(groupPanelLayout);
        groupPanelLayout.setHorizontalGroup(
            groupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(groupPanelLayout.createSequentialGroup()
                .addGroup(groupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(label1)
                    .addComponent(label3)
                    .addGroup(groupPanelLayout.createSequentialGroup()
                        .addComponent(label2)
                        .addGap(3, 3, 3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(groupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(creatorIdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(facilityIdField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(areaNetworkCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        groupPanelLayout.setVerticalGroup(
            groupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(groupPanelLayout.createSequentialGroup()
                .addGroup(groupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label1)
                    .addComponent(areaNetworkCombo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(groupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(facilityIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(groupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label3)
                    .addComponent(creatorIdField, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );

        javax.swing.GroupLayout contentLayout = new javax.swing.GroupLayout(content);
        content.setLayout(contentLayout);
        contentLayout.setHorizontalGroup(
            contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contentLayout.createSequentialGroup()
                .addGroup(contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(contentLayout.createSequentialGroup()
                        .addGap(163, 163, 163)
                        .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(contentLayout.createSequentialGroup()
                        .addGap(86, 86, 86)
                        .addComponent(groupPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(101, Short.MAX_VALUE))
        );
        contentLayout.setVerticalGroup(
            contentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(contentLayout.createSequentialGroup()
                .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(groupPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(195, Short.MAX_VALUE))
        );

        add(content);

    }// </editor-fold>//GEN-END:initComponents

    private void areaNetworkComboItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_areaNetworkComboItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            stateMgr.checkState();
        }
        try {
            adapter.onResult(true);
        } catch (Exception ex) {
            LogWriter.error(getClass(), ex);
        }
    }//GEN-LAST:event_areaNetworkComboItemStateChanged

    private void noJoinAreaNetworkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_noJoinAreaNetworkActionPerformed
        stateMgr.controlJoinArea();

        if (adapter != null) {
            try {
                adapter.onResult(true);
            } catch (Exception ex) {
                  LogWriter.error(getClass(), ex);
            }
        }
    }//GEN-LAST:event_noJoinAreaNetworkActionPerformed

    private void joinAreaNetworkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_joinAreaNetworkActionPerformed
        stateMgr.controlJoinArea();

        if (adapter != null) {
            try {
                adapter.onResult(true);
            } catch (Exception ex) {
                  LogWriter.error(getClass(), ex);
            }
        }
    }//GEN-LAST:event_joinAreaNetworkActionPerformed

    private void creatorIdFieldPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_creatorIdFieldPropertyChange
       if (adapter != null) {
            try {
                adapter.onResult(true);
            } catch (Exception ex) {
                  LogWriter.error(getClass(), ex);
            }
        }
    }//GEN-LAST:event_creatorIdFieldPropertyChange
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox areaNetworkCombo;
    private javax.swing.ButtonGroup bg;
    private javax.swing.JPanel content;
    private javax.swing.JTextField creatorIdField;
    private javax.swing.JTextField facilityIdField;
    private javax.swing.JPanel groupPanel;
    private javax.swing.JRadioButton joinAreaNetwork;
    private javax.swing.JLabel label1;
    private javax.swing.JLabel label2;
    private javax.swing.JLabel label3;
    private javax.swing.JRadioButton noJoinAreaNetwork;
    private javax.swing.JPanel panel1;
    // End of variables declaration//GEN-END:variables

    private void initCustomComponents() {
        networkProjects = GlobalConstants.getNameValuePair("areaNetwork.list");
        areaNetworkCombo.setModel(new DefaultComboBoxModel(networkProjects));
    }

    private void connect() {

        stateMgr = new StateMgr();
        DocumentListener dl = new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                stateMgr.checkState();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                stateMgr.checkState();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                stateMgr.checkState();
            }
        };

        facilityIdField.getDocument().addDocumentListener(dl);
        creatorIdField.getDocument().addDocumentListener(dl);

        // IME OFF FocusAdapter

        facilityIdField.addFocusListener(AutoRomanListener.getInstance());
        creatorIdField.addFocusListener(AutoRomanListener.getInstance());


        stateMgr.controlJoinArea();
    }

    @Override
    public void onChenge(Adapter<Boolean, Boolean> adapter) {
        this.adapter = adapter;
    }

    /**
     * 地域連携設定を開始する。
     */
    @Override
    public void start() {
        //    projectGlobalVariables = GlobalVariables.getGlobalVariables();
        initCustomComponents();

        model.populate();
        connect();
    }

    /**
     * 保存する。
     */
    @Override
    public void save() {
        model.restore();
    }

    @Override
    public String getId() {
        return id;
    }

    /**
     *
     * @param id
     */
    @Override
    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String getTitle() {
        return title;
    }

    @Override
    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String getIcon() {
        return icon;
    }

    /**
     *
     * @param icon
     */
    @Override
    public void setIcon(String icon) {
        this.icon = icon;
    }

    @Override
    public ProjectSettingDialog getContext() {
        return context;
    }

    @Override
    public void setContext(ProjectSettingDialog context) {
        this.context = context;
        this.addPropertyChangeListener(STATE_PROP, context);
        this.setLogInState(context.getLoginState());
    }

    @Override
    public boolean isLoginState() {
        return loginState;
    }

    @Override
    public void setLogInState(boolean login) {
        loginState = login;
    }

    @Override
    public JPanel getPanel() {
        return this;
    }

    @Override
    public void addPropertyChangeListener(String prop, PropertyChangeListener l) {
        boundSupport.addPropertyChangeListener(prop, l);
    }

    @Override
    public void removePropertyChangeListener(String prop, PropertyChangeListener l) {
        boundSupport.removePropertyChangeListener(prop, l);
    }

    /**
     * @param state The state to set.
     */
    @Override
    public void setState(State state) {
        this.state = state;
        boundSupport.firePropertyChange(STATE_PROP, null, this.state);
    }

    /**
     * @return Returns the state.
     */
    @Override
    public State getState() {
        return state;
    }

    class NetworkModel {

        public void populate() {
            boolean join = GlobalVariables.getJoinAreaNetwork();
            joinAreaNetwork.setSelected(join);
            noJoinAreaNetwork.setSelected(!join);

            String val = GlobalVariables.getAreaNetworkName();
            if (val != null) {
                for (int i = 0; i < networkProjects.length; i++) {
                    if (val.equals(networkProjects[i].getValue())) {
                        areaNetworkCombo.setSelectedIndex(i);
                        break;
                    }
                }
            }

            val = GlobalVariables.getAreaNetworkFacilityId();
            val = val != null ? val : "";
            facilityIdField.setText(val);

            val = GlobalVariables.getAreaNetworkCreatorId();
            val = val != null ? val : "";
            creatorIdField.setText(val);

            if (join) {
                areaNetworkCombo.setEnabled(true);
                facilityIdField.setEnabled(true);
                creatorIdField.setEnabled(true);
            }
        }

        public void restore() {
            boolean join = joinAreaNetwork.isSelected();
            GlobalVariables.setJoinAreaNetwork(join);

            NameValuePair pair = (NameValuePair) areaNetworkCombo.getSelectedItem();
            GlobalVariables.setAreaNetworkName(pair.getValue());

            String val = facilityIdField.getText().trim();
            if (!val.equals("")) {
                GlobalVariables.setAreaNetworkFacilityId(val);
            }

            val = creatorIdField.getText().trim();
            if (!val.equals("")) {
                GlobalVariables.setAreaNetworkCreatorId(val);
            }
        }
    }

    class StateMgr {

        public void checkState() {
            State newState = isValid() ? State.VALID_STATE : State.INVALID_STATE;
            if (newState != state) {
                setState(newState);
            }
        }

        public void controlJoinArea() {
            groupPanel.setEnabled(joinAreaNetwork.isSelected());
            areaNetworkCombo.setEnabled(joinAreaNetwork.isSelected());
            creatorIdField.setEnabled(joinAreaNetwork.isSelected());
            facilityIdField.setEnabled(joinAreaNetwork.isSelected());

            this.checkState();
        }

        private boolean isValid() {
            if (joinAreaNetwork.isSelected()) {
                boolean projOk = areaNetworkCombo.getSelectedIndex() != 0;
                boolean facilityOk = !facilityIdField.getText().trim().equals("");
                boolean creatorOk = !creatorIdField.getText().trim().equals("");
                return (projOk && facilityOk && creatorOk);
            }
            return true;
        }
    }
}
