/*
!=======================================================================
!
!  PROGRAM  PHASE-Viewer  (PHASE-Viewer 2014.01 ver.3.3.0)
!
!  Created on 2005/06/03, 18:24
!  AUTHOR(S): KOGA, Junichiro
!  File : SessionCreator.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.ssh;

import java.io.File;

import javax.swing.JOptionPane;
import javax.swing.JTextField;

import ciss.phase_viewer.mainpanel.Desk;
import ciss.phase_viewer.ssh.hosts.HostInfo;
import ciss.phase_viewer.ssh.hosts.MyUserInfo;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * 
 * @author KOGA, Junichiro
 */
public class SessionCreator {
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger
            .getLogger(SessionCreator.class.getName());

    /** Creates a new instance of SessionCreator */
    private SessionCreator() {
    }

    public static Session getSession(HostInfo info) throws JSchException {
        return getSession(info, -1);
    }

    public static Session getSession(HostInfo info, int timeout)
            throws JSchException {
        logger.debug("creating session: ");
        String user = info.getProperty("username");
        String address = info.getProperty("address");

        if (user == null || user.length() == 0) {
            prompt("username", user, info);
            if (user == null || user.length() == 0) {
                logger.info("operation canceled.");
                return null;
            }
        }

        if (address == null || address.length() == 0) {
            prompt("address", address, info);
            if (address == null || address.length() == 0) {
                logger.info("operation canceled.");
                return null;
            }
        }
        int port = 22;
        String sport = info.getProperty("port");
        if (sport != null)
            try {
                port = Integer.parseInt(sport);
            } catch (NumberFormatException nfe) {
            }
        MyUserInfo userinfo = new MyUserInfo(info);
        JSch jsch = ciss.phase_viewer.ssh.KnownHosts.getJSch();
        String pkeySupport = System.getProperty("private_key_support");
        if(pkeySupport!=null&&pkeySupport.equals("true")) {
            String pkey = info.getProperty("private_key_file");
            if (pkey != null && new File(pkey).exists())
                jsch.addIdentity(pkey);
        }
        Session session = jsch.getSession(user, address, port);
        session.setUserInfo(userinfo);
        if (timeout >= 0)
            session.setTimeout(timeout);
        try {
            session.connect();
        } catch (JSchException ex) {
            ex.printStackTrace();
            logger.error("connection failed");
            return null;
        }

        return session;
    }

    private static String prompt(String tag, String str, HostInfo info) {
        JTextField text = new JTextField();
        Object[] ob = { text };
        int result = JOptionPane.showConfirmDialog(Desk.getDesktop(), text,
                "enter " + tag, JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            str = text.getText();
            info.setProperty(tag, str);
            return str;
        } else {
            return null;
        }
    }

}
