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

/*
 * AddFacilityDialog.java
 *
 * Created on 2010/03/08, 17:19:38
 */
//package open.dolphin.client;
/*
import java.util.logging.Level;
import java.util.logging.Logger;
import open.dolphin.project.GlobalConstants;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;

import javax.naming.InitialContext;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

import org.jboss.security.Util;
import org.jboss.security.auth.callback.UsernamePasswordHandler;

import open.dolphin.service.ISystemService;
import open.dolphin.infomodel.UserModel;
import open.dolphin.log.LogWriter;
import org.jdesktop.application.Application;
import org.jdesktop.application.ApplicationContext;
import org.jdesktop.application.Task;
import org.jdesktop.application.TaskMonitor;


public class AddFacilityDialog extends javax.swing.JDialog implements ComponentListener, Runnable {

    public static final String ACCOUNT_INFO = "accountInfo";

    private enum AccountState {

        COM_TEST, AGREEMENT, ACCOUNT_INFO
    };
    private CardLayout cardLayout;
    private PropertyChangeSupport boundSupport;
    private ServerInfo serverInfo;
    private OIDGetter oidGetter;
    private AgreementPanel agreement;
    private AccountInfoPanel accountInfo;
    private AccountState state = AccountState.COM_TEST;
    private boolean comTestOk;
    private boolean agreementOk;
    private boolean accountInfoOk;


    public AddFacilityDialog() {
        super((Frame) null, null, true);
        boundSupport = new PropertyChangeSupport(this);
        initComponents();
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        okBtn = new javax.swing.JButton();
        cancelBtn = new javax.swing.JButton();
        nextBtn = new javax.swing.JButton();
        backBtn = new javax.swing.JButton();
        cardPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        okBtn.setText("jButton1");
        okBtn.setName("okBtn"); // NOI18N

        cancelBtn.setText("jButton2");
        cancelBtn.setName("cancelBtn"); // NOI18N

        nextBtn.setText("jButton3");
        nextBtn.setName("nextBtn"); // NOI18N

        backBtn.setText("jButton4");
        backBtn.setName("backBtn"); // NOI18N

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

        javax.swing.GroupLayout cardPanelLayout = new javax.swing.GroupLayout(cardPanel);
        cardPanel.setLayout(cardPanelLayout);
        cardPanelLayout.setHorizontalGroup(
            cardPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        cardPanelLayout.setVerticalGroup(
            cardPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addComponent(cardPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 76, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(backBtn)
                    .addComponent(nextBtn)
                    .addComponent(cancelBtn)
                    .addComponent(okBtn))
                .addGap(124, 124, 124))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(cardPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(okBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nextBtn)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(backBtn)
                .addContainerGap(149, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backBtn;
    private javax.swing.JButton cancelBtn;
    private javax.swing.JPanel cardPanel;
    private javax.swing.JButton nextBtn;
    private javax.swing.JButton okBtn;
    // End of variables declaration//GEN-END:variables

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

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

    @Override
    public void run() {
        initialize();
        connect();
        cardLayout.show(cardPanel, "comTest");
        this.setVisible(true);
    }

    public void setServerInfo(ServerInfo info) {
        serverInfo = info;
        boundSupport.firePropertyChange(ACCOUNT_INFO, null, serverInfo);
    }


    private void initialize() {

        // リソースから値を取得する
        String windowTitleitle = "アカウント作成";
        int windowWidth = 741;
        int windowHeight = 513;
        String agreementRes = "asp-agreement.txt";
        String agreementEnc = "SHIFT_JIS";

        String backBtnText = "前項";
        String nextBtnText = "次項";
        String cancelBtnText = (String) UIManager.get("OptionPane.cancelButtonText");
        String addBtnText = "=登録";

        // 通信テストパネルを生成する
        oidGetter = new OIDGetter();

        // 使用許諾パネルを生成する
        AgreementModel agreeModel = new AgreementModel();
        try {
            InputStreamReader ir = new InputStreamReader(GlobalConstants.getResourceAsStream(agreementRes), agreementEnc);
            BufferedReader reader = new BufferedReader(ir);
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
            reader.close();
            agreeModel.setAgreeText(sb.toString());
        } catch (Exception e) {
            LogWriter.error(getClass(), e);
            return;
        }
        agreement = new AgreementPanel(agreeModel);

        // アカウント情報パネルを生成する
        accountInfo = new AccountInfoPanel();

        // カードレアイウトへ配置する
        cardPanel = new JPanel();
        cardLayout = new CardLayout();
        cardPanel.setLayout(cardLayout);
        cardLayout.addLayoutComponent(oidGetter, "comTest");
        cardLayout.addLayoutComponent(agreement, "agreement");
        cardLayout.addLayoutComponent(accountInfo, "accountInfo");
        cardPanel.add(oidGetter, "comTest");
        cardPanel.add(agreement, "agreement");
        cardPanel.add(accountInfo, "accountInfo");

        // 戻るボタンを生成する
        //  backBtn = new JButton(backBtnText);
        backBtn.setText(backBtnText);
        backBtn.setEnabled(false);

        // 次項ボタンを生成する
        //    nextBtn = new JButton(nextBtnText);
        nextBtn.setText(nextBtnText);
        nextBtn.setEnabled(false);

        // 登録ボタンを生成する
        //  okBtn = new JButton(addBtnText);
        okBtn.setText(addBtnText);
        okBtn.setEnabled(false);

        // キャンセルボタンを生成する
        //   cancelBtn = new JButton(cancelBtnText);
        cancelBtn.setText(cancelBtnText);

        // ボタンパネルを生成する
        JPanel btnPanel = null;
        if (GlobalConstants.isMac()) {

            btnPanel = new JPanel();
            btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS));
            btnPanel.add(Box.createHorizontalGlue());
            btnPanel.add(backBtn);
            btnPanel.add(Box.createHorizontalStrut(5));
            btnPanel.add(nextBtn);
            btnPanel.add(Box.createHorizontalStrut(5));
            btnPanel.add(cancelBtn);
            btnPanel.add(Box.createHorizontalStrut(5));
            btnPanel.add(okBtn);
            //      btnPanel = GUIFactory.createCommandButtonPanel(new JPanel(), new JButton[]{backBtn, nextBtn, cancelBtn, okBtn});
        } else {
            btnPanel = new JPanel();
            btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.X_AXIS));
            btnPanel.add(Box.createHorizontalGlue());
            btnPanel.add(backBtn);
            btnPanel.add(Box.createHorizontalStrut(5));
            btnPanel.add(nextBtn);
            btnPanel.add(Box.createHorizontalStrut(5));
            btnPanel.add(okBtn);
            btnPanel.add(Box.createHorizontalStrut(5));
            btnPanel.add(cancelBtn);
            //        btnPanel = GUIFactory.createCommandButtonPanel(new JPanel(), new JButton[]{backBtn, nextBtn, okBtn, cancelBtn});
        }

        // 全体を配置する
        JPanel content = new JPanel(new BorderLayout(0, 17));
        content.add(cardPanel, BorderLayout.CENTER);
        content.add(btnPanel, BorderLayout.SOUTH);
        content.setBorder(BorderFactory.createEmptyBorder(12, 12, 11, 11));

        // コンテントにする
        this.getContentPane().add(content, BorderLayout.CENTER);

        // Window の設定を行う
        this.setTitle(GlobalConstants.getFrameTitle(windowTitleitle));
        this.setSize(new Dimension(windowWidth, windowHeight));
        Dimension size = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        int top = (size.height - windowHeight) / 3;
        int left = (size.width - windowWidth) / 2;
        this.setLocation(left, top);
    }


    private void connect() {

        oidGetter.addOidPropertyListener(new OidListener());
        agreement.addAgreePropertyListener(new AgreementListener());
        accountInfo.addValidInfoPropertyListener(new AccountInfoListener());

        backBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (state == AccountState.AGREEMENT) {
                    setState(AccountState.COM_TEST);
                    cardLayout.show(cardPanel, "comTest");
                } else if (state == AccountState.ACCOUNT_INFO) {
                    setState(AccountState.AGREEMENT);
                    cardLayout.show(cardPanel, "agreement");
                }
            }
        });

        nextBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (state == AccountState.COM_TEST) {
                    setState(AccountState.AGREEMENT);
                    cardLayout.show(cardPanel, "agreement");
                } else if (state == AccountState.AGREEMENT) {
                    setState(AccountState.ACCOUNT_INFO);
                    cardLayout.show(cardPanel, "accountInfo");
                }
            }
        });

        okBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                addFacilityAdmin();
            }
        });

        cancelBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                close();
            }
        });

        this.addComponentListener(this);
    }

    class OidListener implements PropertyChangeListener {

        @Override
        public void propertyChange(PropertyChangeEvent e) {
            String oid = (String) e.getNewValue();
            comTestOk = (oid != null && (!oid.equals(""))) ? true : false;
            controlButton();
        }
    }

    class AgreementListener implements PropertyChangeListener {

        @Override
        public void propertyChange(PropertyChangeEvent e) {
            boolean agree = ((Boolean) e.getNewValue()).booleanValue();
            agreementOk = agree;
            controlButton();
        }
    }

    class AccountInfoListener implements PropertyChangeListener {

        @Override
        public void propertyChange(PropertyChangeEvent e) {
            boolean account = ((Boolean) e.getNewValue()).booleanValue();
            accountInfoOk = account;
            controlButton();
        }
    }

    private void setState(AccountState s) {
        state = s;
        controlButton();
    }

    private void controlButton() {

        backBtn.setEnabled(false);
        nextBtn.setEnabled(false);
        okBtn.setEnabled(false);

        switch (state) {

            case COM_TEST:
                nextBtn.setEnabled(comTestOk);
                break;

            case AGREEMENT:
                backBtn.setEnabled(true);
                nextBtn.setEnabled(agreementOk);
                break;

            case ACCOUNT_INFO:
                backBtn.setEnabled(true);
                okBtn.setEnabled(accountInfoOk);
                break;
        }
    }

    private void close() {
        setVisible(false);
        dispose();
    }


    private void addFacilityAdmin() {

        // 登録するユーザモデルを得る
        UserModel model = accountInfo.getModel();

        // Password の hash化を行う
        String userId = model.getUserId();
        String Algorithm = "MD5";
        String encoding = "hex";
        String charset = null;
        String hashPass = Util.createPasswordHash(Algorithm, encoding, charset, userId, model.getPassword());
        model.setPassword(hashPass);

        ApplicationContext appCtx = GlobalConstants.getApplicationContext();
        Application app = appCtx.getApplication();

        AddFacilityTask task = new AddFacilityTask(app, model);
        try {
            task.succeeded(task.doInBackground());
        } catch (Exception ex) {
            Logger.getLogger(AddFacilityDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
        //   TaskMonitor taskMonitor = appCtx.getTaskMonitor();
        //   String message = "アカウント登録";
        //   String note = userId + "を登録しています...";
        //   Component c = SwingUtilities.getWindowAncestor(this);
        //   TaskTimerMonitor w = new TaskTimerMonitor(task, taskMonitor, c, message, note, 200, 60 * 1000);
        //   taskMonitor.addPropertyChangeListener(w);
        //   appCtx.getTaskService().execute(task);
    }


    //  class AddFacilityTask extends Task<Void, Void> {
    class AddFacilityTask {

        private UserModel user;

        public AddFacilityTask(Application app, UserModel user) {
            //        super(app);
            this.user = user;
        }

        protected Void doInBackground() throws Exception {

            // SECURITY
            String qid = "minagawa";
            String password = "hanagui+";
            String securityDomain = "openDolphinSysAd";
            String providerURL = "jnp://210.153.124.60:1099";

            UsernamePasswordHandler h = new UsernamePasswordHandler(qid, password.toCharArray());
            LoginContext lc = new LoginContext(securityDomain, h);
            lc.login();

            Properties props = new Properties();
            props.setProperty("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
            props.setProperty("java.naming.provider.url", providerURL);
            props.setProperty("java.naming.factory.url.pkgs", "org.jboss.namingrg.jnp.interfaces");
            InitialContext ctx = new InitialContext(props);

            ISystemService service = (ISystemService) ctx.lookup("openDolphin/RemoteSystemService");
            service.addFacilityAdmin(user);

            return null;
        }

        protected void succeeded(Void result) {
            LogWriter.warn(AddFacilityDialog.class, "Task succeeded");
            okBtn.setEnabled(false);

            // 成功メッセージを表示する
            StringBuilder sb = new StringBuilder();
            sb.append("ご依頼の内容に基づき、アカウントを作成しました。"); //GlobalVariables.getString("account.task.successMsg1"));
            sb.append("\n");
            sb.append("またご登録いただいた電子メールアドレスに施設IDを送付しました。"); //GlobalVariables.getString("account.task.successMsg2"));
            sb.append("\n");
            sb.append("お受け取りになったIDを、設定画面の[施設ID欄]にコピーペーストし"); //GlobalVariables.getString("account.task.successMsg3"));
            sb.append("\n");
            sb.append("ログインを行ってください。");
            JOptionPane.showMessageDialog(AddFacilityDialog.this, sb.toString(), AddFacilityDialog.this.getTitle(), JOptionPane.INFORMATION_MESSAGE);

            // サーバアカウント情報を通知する
            ServerInfo info = new ServerInfo();
            info.setAdminId(user.getUserId());
            setServerInfo(info);

            AddFacilityDialog.this.setVisible(false);
            AddFacilityDialog.this.dispose();
        }

        protected void failed(java.lang.Throwable cause) {
            LogWriter.warn(AddFacilityDialog.class, cause.getMessage());
            String errMsg = null;
            if (cause instanceof javax.ejb.EJBAccessException) {
                LogWriter.error(AddFacilityDialog.class, "システム設定エラー", cause);
                StringBuilder sb = new StringBuilder();
                sb.append("システム設定エラー");
                errMsg = sb.toString();
            } else if (cause instanceof javax.naming.CommunicationException) {
                LogWriter.error(AddFacilityDialog.class, "ASPサーバに接続できません。", cause);
                StringBuilder sb = new StringBuilder();
                sb.append("ASPサーバに接続できません。");
                sb.append("\n");
                sb.append("ファイヤーウォール等がサービスを利用できない設定になっている可能性があります。");
                errMsg = sb.toString();
            } else if (cause instanceof javax.naming.NamingException) {
                LogWriter.error(AddFacilityDialog.class, "サーバーがビジーの可能性があります。しばらく間をおいて再度実行してみてください。(AddFacilityDialog)", cause);
                StringBuilder sb = new StringBuilder();
                sb.append("サーバーがビジーの可能性があります。しばらく間をおいて再度実行してみてください。(AddFacilityDialog)");
                errMsg = sb.toString();
            } else if (cause instanceof LoginException) {
                LogWriter.error(AddFacilityDialog.class, "クライアントの環境が実行を許可されない設定になっている可能性があります。", cause);
                StringBuilder sb = new StringBuilder();
                sb.append("セキュリティエラーが生じました。");
                sb.append("\n");
                sb.append("クライアントの環境が実行を許可されない設定になっている可能性があります。");
                errMsg = sb.toString();
            } else if (cause instanceof Exception) {
                LogWriter.error(AddFacilityDialog.class, "サーバーがビジーの可能性があります", cause);
                StringBuilder sb = new StringBuilder();
                sb.append("サーバーがビジーの可能性があります。しばらく間をおいて再度実行してみてください。");
                errMsg = sb.toString();
            }

            String title = AddFacilityDialog.this.getTitle();
            JOptionPane.showMessageDialog(AddFacilityDialog.this, errMsg, title, JOptionPane.WARNING_MESSAGE);

        }

        protected void interrupted(java.lang.InterruptedException e) {
            LogWriter.warn(AddFacilityDialog.class, e.getMessage());
        }

        protected void cancelled() {
            LogWriter.debug(AddFacilityDialog.class, "Task cancelled");
        }

    }

    @Override
    public void componentMoved(java.awt.event.ComponentEvent componentEvent) {
    }

    @Override
    public void componentResized(java.awt.event.ComponentEvent componentEvent) {
    }

    @Override
    public void componentShown(java.awt.event.ComponentEvent componentEvent) {
    }

    @Override
    public void componentHidden(java.awt.event.ComponentEvent componentEvent) {
    }
}
*/