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

/*
 * SDialogFilterCompanyBranchEntity.java
 *
 * Created on 11/01/2010, 05:47:27 PM
 */

package erp.mbps.form;

import erp.data.SDataConstantsSys;
import erp.lib.SLibConstants;
import erp.lib.form.SFormComponentItem;
import erp.lib.form.SFormField;
import erp.lib.form.SFormUtilities;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import java.util.Vector;

/**
 *
 * @author Alfonso Flores, Sergio Flores
 */
public class SDialogFilterCompanyBranchEntity extends javax.swing.JDialog implements erp.lib.form.SFormInterface, java.awt.event.ActionListener {

    private int mnFormType;
    private int mnFormResult;
    private int mnFormStatus;
    private boolean mbFirstTime;
    private boolean mbResetingForm;
    private java.util.Vector<erp.lib.form.SFormField> mvFields;
    private erp.client.SClientInterface miClient;

    private erp.lib.form.SFormField moFieldCompanyBranchId;
    private erp.lib.form.SFormField moFieldEntity;

    private int mnEntityCategoryId;
    private int mnCompanyBranchId;
    private int mnEntityId;

    /** Creates new form SDialogFilterCompanyBranchEntity */
    public SDialogFilterCompanyBranchEntity(erp.client.SClientInterface client, int entityCategoryId) {
        super(client.getFrame(), true);
        miClient = client;
        mnEntityCategoryId = entityCategoryId;

        initComponents();
        initComponentsExtra();
    }

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

        jCheckBox1 = new javax.swing.JCheckBox();
        jpOptions = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jckAllCompanyBranch = new javax.swing.JCheckBox();
        jckUniversalCompany = new javax.swing.JCheckBox();
        jPanel4 = new javax.swing.JPanel();
        jlCompanyBranch = new javax.swing.JLabel();
        jcbCompanyBranch = new javax.swing.JComboBox<SFormComponentItem>();
        jPanel7 = new javax.swing.JPanel();
        jckAllEntity = new javax.swing.JCheckBox();
        jckUniversalCompanyBranch = new javax.swing.JCheckBox();
        jPanel5 = new javax.swing.JPanel();
        jlEntity = new javax.swing.JLabel();
        jspEntity = new javax.swing.JScrollPane();
        jltEntity = new javax.swing.JList<SFormComponentItem>();
        jpControls = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jbSelectSession = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jbOk = new javax.swing.JButton();
        jbCancel = new javax.swing.JButton();

        jCheckBox1.setText("jCheckBox1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Sucursales y entidades");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jpOptions.setBorder(javax.swing.BorderFactory.createTitledBorder("Opciones disponibles:"));
        jpOptions.setLayout(new java.awt.BorderLayout(0, 5));

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

        jPanel6.setLayout(new java.awt.BorderLayout());

        jckAllCompanyBranch.setText("Todas las sucursales");
        jckAllCompanyBranch.setPreferredSize(new java.awt.Dimension(125, 23));
        jckAllCompanyBranch.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jckAllCompanyBranchItemStateChanged(evt);
            }
        });
        jPanel6.add(jckAllCompanyBranch, java.awt.BorderLayout.CENTER);

        jckUniversalCompany.setText("Acceso universal");
        jckUniversalCompany.setEnabled(false);
        jckUniversalCompany.setPreferredSize(new java.awt.Dimension(125, 23));
        jPanel6.add(jckUniversalCompany, java.awt.BorderLayout.EAST);

        jPanel3.add(jPanel6);

        jPanel4.setLayout(new java.awt.BorderLayout());

        jlCompanyBranch.setText("Sucursal de la empresa: *");
        jlCompanyBranch.setPreferredSize(new java.awt.Dimension(135, 23));
        jPanel4.add(jlCompanyBranch, java.awt.BorderLayout.WEST);

        jcbCompanyBranch.setPreferredSize(new java.awt.Dimension(225, 23));
        jcbCompanyBranch.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbCompanyBranchItemStateChanged(evt);
            }
        });
        jPanel4.add(jcbCompanyBranch, java.awt.BorderLayout.CENTER);

        jPanel3.add(jPanel4);

        jPanel7.setLayout(new java.awt.BorderLayout());

        jckAllEntity.setText("Todas las entidades");
        jckAllEntity.setPreferredSize(new java.awt.Dimension(125, 23));
        jckAllEntity.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jckAllEntityItemStateChanged(evt);
            }
        });
        jPanel7.add(jckAllEntity, java.awt.BorderLayout.CENTER);

        jckUniversalCompanyBranch.setText("Acceso universal");
        jckUniversalCompanyBranch.setEnabled(false);
        jckUniversalCompanyBranch.setPreferredSize(new java.awt.Dimension(125, 23));
        jPanel7.add(jckUniversalCompanyBranch, java.awt.BorderLayout.EAST);

        jPanel3.add(jPanel7);

        jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));

        jlEntity.setText("Seleccionar entidad:");
        jlEntity.setPreferredSize(new java.awt.Dimension(350, 23));
        jPanel5.add(jlEntity);

        jPanel3.add(jPanel5);

        jpOptions.add(jPanel3, java.awt.BorderLayout.NORTH);

        jspEntity.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        jltEntity.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jltEntity.setToolTipText(SDataConstantsSys.TXT_DOUBLE_CLICK);
        jltEntity.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jltEntityMouseClicked(evt);
            }
        });
        jltEntity.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jltEntityKeyPressed(evt);
            }
        });
        jspEntity.setViewportView(jltEntity);

        jpOptions.add(jspEntity, java.awt.BorderLayout.CENTER);

        getContentPane().add(jpOptions, java.awt.BorderLayout.CENTER);

        jpControls.setPreferredSize(new java.awt.Dimension(392, 33));
        jpControls.setLayout(new java.awt.GridLayout(1, 2));

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jbSelectSession.setText("Sesión");
        jbSelectSession.setPreferredSize(new java.awt.Dimension(75, 23));
        jPanel1.add(jbSelectSession);

        jpControls.add(jPanel1);

        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        jbOk.setText("Aceptar");
        jbOk.setToolTipText("[Ctrl + Enter]");
        jbOk.setPreferredSize(new java.awt.Dimension(75, 23));
        jPanel2.add(jbOk);

        jbCancel.setText("Cancelar");
        jbCancel.setToolTipText("[Escape]");
        jPanel2.add(jbCancel);

        jpControls.add(jPanel2);

        getContentPane().add(jpControls, java.awt.BorderLayout.SOUTH);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-488)/2, (screenSize.height-334)/2, 488, 334);
    }// </editor-fold>//GEN-END:initComponents

    private void jcbCompanyBranchItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbCompanyBranchItemStateChanged
        if (!mbResetingForm) {
            if (evt.getStateChange() == ItemEvent.SELECTED) {
                itemStateChangedCompanyBranch();
            }
        }
    }//GEN-LAST:event_jcbCompanyBranchItemStateChanged

    private void jckAllCompanyBranchItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jckAllCompanyBranchItemStateChanged
        if (!mbResetingForm) {
            if (jckAllCompanyBranch.isSelected()) {
                jcbCompanyBranch.setEnabled(false);
                jcbCompanyBranch.setSelectedIndex(0);
            }
            else {
                jcbCompanyBranch.setEnabled(true);
            }
        }
    }//GEN-LAST:event_jckAllCompanyBranchItemStateChanged

    private void jckAllEntityItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jckAllEntityItemStateChanged
        if (!mbResetingForm) {
            if (jckAllEntity.isSelected()) {
                jlEntity.setEnabled(false);
                jltEntity.setEnabled(false);
                jltEntity.clearSelection();
            }
            else {
                jlEntity.setEnabled(jcbCompanyBranch.getSelectedIndex() > 0);
                jltEntity.setEnabled(jcbCompanyBranch.getSelectedIndex() > 0);
            }
        }
    }//GEN-LAST:event_jckAllEntityItemStateChanged

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        windowActivated();
    }//GEN-LAST:event_formWindowActivated

    private void jltEntityMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jltEntityMouseClicked
        if (evt.getClickCount() == 2) {
            actionOk();
        }
    }//GEN-LAST:event_jltEntityMouseClicked

    private void jltEntityKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jltEntityKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            actionOk();
        }
    }//GEN-LAST:event_jltEntityKeyPressed

    private void initComponentsExtra() {
        jckUniversalCompany.setSelected(miClient.getSessionXXX().getIsUniversal() || miClient.getSessionXXX().getIsUniversalCompany(miClient.getSessionXXX().getCompany().getPkCompanyId()));
        jckAllCompanyBranch.setEnabled(jckUniversalCompany.isSelected());

        switch (mnEntityCategoryId) {
            case SDataConstantsSys.CFGS_CT_ENT_CASH:
                jlEntity.setText("Seleccionar cuenta de efectivo: *");
                jckAllEntity.setText("Todas las cuentas de efectivo");
                jbSelectSession.setToolTipText("Seleccionar cuentas de efectivo actual");
                setTitle("Sucursales y cuentas de efectivo");
                break;
            case SDataConstantsSys.CFGS_CT_ENT_WH:
                jlEntity.setText("Seleccionar almacén: *");
                jckAllEntity.setText("Todos los almacenes");
                jbSelectSession.setToolTipText("Seleccionar almacén actual");
                setTitle("Sucursales y almacenes");
                break;
            case SDataConstantsSys.CFGS_CT_ENT_POS:
                jlEntity.setText("Seleccionar punto de venta: *");
                jckAllEntity.setText("Todos los puntos de venta");
                jbSelectSession.setToolTipText("Seleccionar punto de venta actual");
                setTitle("Sucursales y puntos de venta");
                break;
            case SDataConstantsSys.CFGS_CT_ENT_PLANT:
                jlEntity.setText("Seleccionar planta: *");
                jckAllEntity.setText("Todas las plantas");
                jbSelectSession.setToolTipText("Seleccionar planta actual");
                setTitle("Sucursales y plantas");
                break;
            default:
                miClient.showMsgBoxWarning(SLibConstants.MSG_ERR_UTIL_UNKNOWN_OPTION);
        }

        moFieldCompanyBranchId = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbCompanyBranch, jlCompanyBranch);
        moFieldEntity = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jltEntity, jlEntity);

        mvFields = new Vector<SFormField>();
        mvFields.add(moFieldCompanyBranchId);
        mvFields.add(moFieldEntity);

        jbOk.addActionListener(this);
        jbCancel.addActionListener(this);
        jbSelectSession.addActionListener(this);

        SFormUtilities.createActionMap(getRootPane(), this, "actionOk", "ok", KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK);
        SFormUtilities.createActionMap(getRootPane(), this, "actionCancel", "cancel", KeyEvent.VK_ESCAPE, 0);
    }

    private void windowActivated() {
        if (mbFirstTime) {
            mbFirstTime = false;

            if (jltEntity.isEnabled()) {
                jltEntity.requestFocus();
            }
            else if (jcbCompanyBranch.isEnabled()) {
                jcbCompanyBranch.requestFocus();
            }
            else {
                jbOk.requestFocus();
            }
        }
    }

    private boolean isUniversalCompany() {
        return jckUniversalCompany.isSelected();
    }

    private boolean isUniversalCompanyBranch() {
        return jckUniversalCompany.isSelected() || miClient.getSessionXXX().getIsUniversalCompanyBranch(moFieldCompanyBranchId.getKeyAsIntArray()[0]) || miClient.getSessionXXX().getIsUniversalCompanyBranchEntities(moFieldCompanyBranchId.getKeyAsIntArray()[0], mnEntityCategoryId);
    }

    private void itemStateChangedCompanyBranch() {
        boolean universal = false;
        Vector<SFormComponentItem> items = null;

        if (jcbCompanyBranch.getSelectedIndex() <= 0) {
            jckUniversalCompanyBranch.setSelected(false);

            jckAllEntity.setEnabled(false);
            jckAllEntity.setSelected(false);

            jlEntity.setEnabled(false);
            jltEntity.setEnabled(false);
            jltEntity.clearSelection();

            jltEntity.setListData(new SFormComponentItem[] {});
        }
        else {
            universal = isUniversalCompanyBranch();

            jckUniversalCompanyBranch.setSelected(universal);

            jckAllEntity.setEnabled(universal);
            jckAllEntity.setSelected(false);

            jlEntity.setEnabled(true);
            jltEntity.setEnabled(true);

            if (universal) {
                items = miClient.getSessionXXX().getAllCompanyBranchEntitiesAsComponentItems(moFieldCompanyBranchId.getKeyAsIntArray()[0], mnEntityCategoryId, false);
            }
            else {
                items = miClient.getSessionXXX().getUserCompanyBranchEntitiesAsComponentItems(moFieldCompanyBranchId.getKeyAsIntArray()[0], mnEntityCategoryId, false);
            }

            jltEntity.setListData(items);
        }
    }

    public void actionOk() {
        if (!jckAllCompanyBranch.isSelected() && jcbCompanyBranch.getSelectedIndex() <= 0) {
            miClient.showMsgBoxWarning(SLibConstants.MSG_ERR_GUI_FIELD_EMPTY + "'" + jlCompanyBranch.getText() + "'.");
            jcbCompanyBranch.requestFocus();
        }
        else if (!jckAllCompanyBranch.isSelected() && !jckAllEntity.isSelected() && jltEntity.getSelectedIndex() == -1) {
            miClient.showMsgBoxWarning(SLibConstants.MSG_ERR_GUI_FIELD_EMPTY + "'" + jlEntity.getText() + "'.");
            jltEntity.requestFocus();
        }
        else {
            mnCompanyBranchId = jckAllCompanyBranch.isSelected() ? SLibConstants.UNDEFINED : moFieldCompanyBranchId.getKeyAsIntArray()[0];
            mnEntityId = jckAllCompanyBranch.isSelected() || jckAllEntity.isSelected() ? SLibConstants.UNDEFINED : moFieldEntity.getKeyAsIntArray()[1];

            mnFormResult = SLibConstants.FORM_RESULT_OK;
            setVisible(false);
        }
    }

    public void actionCancel() {
        mnFormResult = SLibConstants.FORM_RESULT_CANCEL;
        setVisible(false);
    }

    public void actionSelectSession() {
        int[] key = miClient.getSessionXXX().getCurrentCompanyBranchEntityKey(mnEntityCategoryId);

        if (key == null) {
            if (miClient.getSessionXXX().getCurrentCompanyBranchId() != SLibConstants.UNDEFINED) {
                key = new int[] { miClient.getSessionXXX().getCurrentCompanyBranchId(), SLibConstants.UNDEFINED };
            }
        }

        setCompanyBranchEntityKey(key);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JButton jbCancel;
    private javax.swing.JButton jbOk;
    private javax.swing.JButton jbSelectSession;
    private javax.swing.JComboBox<SFormComponentItem> jcbCompanyBranch;
    private javax.swing.JCheckBox jckAllCompanyBranch;
    private javax.swing.JCheckBox jckAllEntity;
    private javax.swing.JCheckBox jckUniversalCompany;
    private javax.swing.JCheckBox jckUniversalCompanyBranch;
    private javax.swing.JLabel jlCompanyBranch;
    private javax.swing.JLabel jlEntity;
    private javax.swing.JList<SFormComponentItem> jltEntity;
    private javax.swing.JPanel jpControls;
    private javax.swing.JPanel jpOptions;
    private javax.swing.JScrollPane jspEntity;
    // End of variables declaration//GEN-END:variables

    public void setCompanyBranchEntityKey(int[] key) {
        if (key == null) {
            mnCompanyBranchId = SLibConstants.UNDEFINED;
            mnEntityId = SLibConstants.UNDEFINED;

            jckAllCompanyBranch.setSelected(false);
            jckAllCompanyBranchItemStateChanged(null);

            moFieldCompanyBranchId.setKey(null);
            itemStateChangedCompanyBranch();

            jckAllEntity.setSelected(false);
            jckAllEntityItemStateChanged(null);

            moFieldEntity.setKey(null);
        }
        else {
            mnCompanyBranchId = key[0];
            mnEntityId = key[1];

            jckAllCompanyBranch.setSelected(mnCompanyBranchId == SLibConstants.UNDEFINED && isUniversalCompany());
            jckAllCompanyBranchItemStateChanged(null);

            moFieldCompanyBranchId.setKey(getCompanyBranchKey());
            itemStateChangedCompanyBranch();

            jckAllEntity.setSelected(mnEntityId == SLibConstants.UNDEFINED && isUniversalCompanyBranch() && !jckAllCompanyBranch.isSelected());
            jckAllEntityItemStateChanged(null);

            moFieldEntity.setKey(getCompanyBranchEntityKey());
        }
    }

    public int[] getCompanyBranchKey() {
        return new int[] { mnCompanyBranchId };
    }

    public int[] getCompanyBranchEntityKey() {
        return new int[] { mnCompanyBranchId, mnEntityId };
    }

    @Override
    public void formClearRegistry() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void formReset() {
        mbResetingForm = true;

        mnFormResult = SLibConstants.UNDEFINED;
        mnFormStatus = SLibConstants.UNDEFINED;
        mbFirstTime = true;

        for (int i = 0; i < mvFields.size(); i++) {
            ((erp.lib.form.SFormField) mvFields.get(i)).resetField();
        }

        mnCompanyBranchId = SLibConstants.UNDEFINED;
        mnEntityId = SLibConstants.UNDEFINED;

        jckAllCompanyBranch.setSelected(false);
        jckAllEntity.setSelected(false);

        mbResetingForm = false;
    }

    @Override
    public void formRefreshCatalogues() {
        Vector<SFormComponentItem> items = null;

        if (isUniversalCompany()) {
            items = miClient.getSessionXXX().getAllCompanyBranchesAsComponentItems(true);
        }
        else {
            items = miClient.getSessionXXX().getUserCompanyBranchesAsComponentItems(true);
        }

        jcbCompanyBranch.removeAllItems();
        for (SFormComponentItem item : items) {
            jcbCompanyBranch.addItem(item);
        }
    }

    @Override
    public erp.lib.form.SFormValidation formValidate() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void setFormStatus(int status) {
        mnFormStatus = status;
    }

    @Override
    public void setFormVisible(boolean visible) {
        setVisible(visible);
    }

    @Override
    public int getFormStatus() {
        return mnFormStatus;
    }

    @Override
    public int getFormResult() {
        return mnFormResult;
    }

    @Override
    public void setRegistry(erp.lib.data.SDataRegistry registry) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public erp.lib.data.SDataRegistry getRegistry() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void setValue(int type, java.lang.Object value) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public java.lang.Object getValue(int type) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public javax.swing.JLabel getTimeoutLabel() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void actionPerformed(java.awt.event.ActionEvent e) {
        if (e.getSource() instanceof javax.swing.JButton) {
            javax.swing.JButton button = (javax.swing.JButton) e.getSource();

            if (button == jbOk) {
                actionOk();
            }
            else if (button == jbCancel) {
                actionCancel();
            }
            else if (button == jbSelectSession) {
                actionSelectSession();
            }
        }
    }
}
