/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on ----
!  AUTHOR(S): KOGA, Junichiro
!  File : PathSelector.java
!  
!  Contact address :  Phase System Consortium
!                     E-mail: phase_system@nims.go.jp URL https://azuma.nims.go.jp
!
!
!   Since 2002, this program set had been intensively developed as a part of the following 
!  national projects supported by the Ministry of Education, Culture, Sports, Science and
!  Technology (MEXT) of Japan; "Frontier Simulation Software for Industrial Science
!  (FSIS)" from 2002 to 2005, "Revolutionary Simulation Software (RSS21)" from 2006 to
!  2008. "Research and Development of Innovative Simulation Software (RISS)" from 2008
!  to 2013. These projects is lead by the Center for Research on Innovative Simulation 
!  Software (CISS), the Institute of Industrial Science (IIS), the University of Tokyo.
!   Since 2013, this program set has been further developed centering on PHASE System
!  Consortium. 
!   The activity of development of this program set has been supervised by Takahisa Ohno.
!
!=======================================================================
 */
package ciss.phase_viewer.common;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;

import ciss.phase_viewer.ssh.SessionCreator;
import ciss.phase_viewer.ssh.SshClient;
import ciss.phase_viewer.ssh.hosts.HostInfo;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;

public class PathSelector extends JPanel {
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger
            .getLogger(PathSelector.class.getName());

    public static final int FILE = 0;
    public static final int DIRECTORY_ONLY = 1;

    public static final int FILE_PROJ_BROWSER = 0;
    public static final int DIRECTORY_ONLY_PROJ_BROWSER = 1;

    private int mode = DIRECTORY_ONLY;
    private String title;
    private int width = 20;

    private JTextField textfield;
    private HostInfo hostinfo;

    private boolean isRemote = false;
    private SshClient sshclient;

    private JButton button;

    public PathSelector(String title) {
        super();
        this.title = title;
        init();
    }

    public PathSelector(String title, int width) {
        super();
        this.title = title;
        this.width = width;
        init();
    }

    public PathSelector(String title, int width, int mode) {
        super();
        this.title = title;
        this.width = width;
        this.mode = mode;
        init();
    }

    public PathSelector(String title, JTextField textfield) {
        super();
        this.title = title;
        this.textfield = textfield;
        init();
    }

    public PathSelector(String title, int width, JTextField textfield) {
        super();
        this.title = title;
        this.width = width;
        this.textfield = textfield;
        init();
    }

    public PathSelector(String title, int width, int mode, JTextField textfield) {
        super();
        this.title = title;
        this.width = width;
        this.mode = mode;
        this.textfield = textfield;
        init();
    }

    public PathSelector(String title, boolean isRemote) {
        super();
        this.title = title;
        this.isRemote = isRemote;
        init();
    }

    public PathSelector(String title, int width, boolean isRemote) {
        super();
        this.title = title;
        this.width = width;
        this.isRemote = isRemote;
        init();
    }

    public PathSelector(String title, int width, int mode, boolean isRemote) {
        super();
        this.title = title;
        this.width = width;
        this.mode = mode;
        this.isRemote = isRemote;
        init();
    }

    public PathSelector(String title, JTextField textfield, boolean isRemote) {
        super();
        this.title = title;
        this.textfield = textfield;
        this.isRemote = isRemote;
        init();
    }

    public PathSelector(String title, int width, JTextField textfield,
            boolean isRemote) {
        super();
        this.title = title;
        this.width = width;
        this.textfield = textfield;
        this.isRemote = isRemote;
        init();
    }

    public PathSelector(String title, int width, int mode,
            JTextField textfield, boolean isRemote) {
        super();
        this.title = title;
        this.width = width;
        this.mode = mode;
        this.textfield = textfield;
        this.isRemote = isRemote;
        init();
    }

    private void init() {
        this.setBorder(new TitledBorder(title));
        this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
        if (textfield == null) {
            textfield = new JTextField(width);
        }
        this.add(textfield);
        button = new JButton("choose...");
        this.add(button);
        int x = button.getSize().width;
        int y = button.getSize().height;
        textfield.setPreferredSize(new Dimension(x, y));

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                bootFileChooser();
            }
        });
    }

    public String getPath() {
        return Utils.getPathDQ(textfield.getText());
    }

    public String getRawPath() {
        return textfield.getText().trim();
    }

    public void setPath(String path) {
        this.textfield.setText(path);
    }

    public void setHostInfo(boolean isRemote) {
        this.isRemote = isRemote;
    }

    public void setSshClient(SshClient sshclient_) {
        this.sshclient = sshclient_;
        ActionListener[] lis = button.getActionListeners();
        if (lis != null) {
            for (int i = 0; i < lis.length; i++) {
                button.removeActionListener(lis[i]);
            }
        }
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                hostinfo = sshclient.getHostInfo();
                bootFileChooser();
            }
        });
    }

    private void bootFileChooser() {
        // implementation of remote file chooser ... pending.
        // ChannelSftp c = null;
        // if ( hostinfo != null ) {
        // c = connect();
        // }
        boolean proj = mode == FILE_PROJ_BROWSER
                || mode == DIRECTORY_ONLY_PROJ_BROWSER;
        ChaseFileChooser fdlg = new ChaseFileChooser(ChaseFileChooser.path,
                proj);
        // RemoteFileChooser fdlg = new RemoteFileChooser(c);
        fdlg.setDialogType(JFileChooser.CUSTOM_DIALOG);
        fdlg.setDialogTitle("choose");
        fdlg.setCurrentDirectory(new File(System.getProperty("user.dir")));

        if (mode == FILE) {
            fdlg.setFileSelectionMode(JFileChooser.FILES_ONLY);
        } else if (mode == DIRECTORY_ONLY) {
            fdlg.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        } else {
            System.out.println("wrong specification of mode");
            return;
        }

        if (fdlg.showDialog(this, "Select") != JFileChooser.APPROVE_OPTION) {
            return;
        }

        textfield.setText(fdlg.getSelectedFile().getAbsolutePath());
    }

    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        textfield.setEnabled(enabled);
        button.setEnabled(enabled);
    }

    public JTextField getTextField() {
        return this.textfield;
    }

    public void setTextField(JTextField textfield) {
        this.textfield = textfield;
    }

    private ChannelSftp connect() {
        ChannelSftp c = null;

        if (hostinfo.isLocalHost()) {
            return null;
        }

        try {
            logger.debug("starting connection...");
            Session session = SessionCreator.getSession(hostinfo);
            Channel channel = session.openChannel("sftp");
            channel.connect();
            c = (ChannelSftp) channel;
            logger.info("sftp connection to host: " + hostinfo.getName());
            logger.debug("current directory: " + c.pwd());
        } catch (Exception exc) {
            logger.error("failed connection");
        }
        return c;
    }
}
