package graphTool;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Calendar;
import java.util.Vector;
import javax.swing.*;
import com.sshtools.j2ssh.SftpClient;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.sftp.SftpFile;
import com.sshtools.j2ssh.transport.IgnoreHostKeyVerification;

public class LogDownloader
{
   private static LogDownloader instance = null;
   private final int ONTEXT    = 9;
   private final int OFFTEXT   = 10;
   private final int DIRTEXT   = 10;
   public static final int ONCAMPUS  = 0;
   public static final int OFFCAMPUS = 1;
   
   public static LogDownloader getInstance()
   {
      if(instance == null)
         instance = new LogDownloader();
      return instance;
   }
   
   private LogDownloader() {}
   
   @SuppressWarnings("unchecked")
   public void downloadLogs(JFrame parent, int source)
   {
      Calendar cal = Calendar.getInstance();
      int month    = cal.get(Calendar.MONTH) + 1; // months are 0 based
      int day      = cal.get(Calendar.DAY_OF_MONTH);
      int year     = cal.get(Calendar.YEAR);
      
      String cwd = System.getProperty("user.dir");
      String os  = System.getProperty("os.name");
      
      // OS independent way of making the directory
      java.io.File dir = new java.io.File(month+"-"+day+"-"+year+"_logs");
      dir.mkdir();
            
      SshClient ssh = new SshClient();
      PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
      try
      {
         // read server address from config file
         BufferedReader fr = new BufferedReader(new FileReader("tcra.config"));
         String directory = fr.readLine().substring(DIRTEXT);
         
         // this will skip 'source' many lines to get the right address
         for(int i = 0; i < source; ++i) fr.readLine();
         String serverAddr = fr.readLine();
                  
         fr.close();
         
         if(source == ONCAMPUS)
            serverAddr = serverAddr.substring(ONTEXT);
         else if(source == OFFCAMPUS)
            serverAddr = serverAddr.substring(OFFTEXT);
         ssh.connect(serverAddr, new IgnoreHostKeyVerification());
         
         // prompt user for username and password
         pwd.setUsername(JOptionPane.showInputDialog("Enter User Name"));
         JPasswordField pwdf = new JPasswordField(10);
         int action = JOptionPane.showConfirmDialog(null, pwdf,"Enter Password",JOptionPane.OK_CANCEL_OPTION);
         if(action >= 0) pwd.setPassword(new String(pwdf.getPassword()));
         else
         {
            ssh.disconnect();
            JOptionPane.showMessageDialog(parent, "Connection Aborted");
            return;
         } // end else
         
         int result = ssh.authenticate(pwd);
         
         if(result == AuthenticationProtocolState.FAILED ||
            result == AuthenticationProtocolState.PARTIAL)
         {
            JOptionPane.showMessageDialog(parent, "Authentication Failed",
                                          "SFTP Failure",
                                          JOptionPane.ERROR_MESSAGE);
            ssh.disconnect();
            return;
         } // end if
         
         // Perform FTP actions over SSH connection
         SftpClient sftp = ssh.openSftpClient();
         if(os.equals("Windows"))
            sftp.lcd(cwd+"\\"+month+"-"+day+"-"+year+"_logs");
         else sftp.lcd(cwd+"/"+month+"-"+day+"-"+year+"_logs");
         sftp.cd(directory+"/tcraLogs");
         Vector<SftpFile> items = new Vector<SftpFile>(sftp.ls());
         
         int count = 0; // count number of files being downloaded
         for(int i = 0; i < items.size(); ++i)
         {
            String name = items.elementAt(i).getFilename();
            if(!(name.equals(".") || name.equals("..")))
            {
               sftp.get(name);
               ++count;
            } // end if
         } // end for
         
         sftp.quit();
         ssh.disconnect();
         
         // done
         JOptionPane.showMessageDialog(parent, count+" files retrieved",
                                       "Success",
                                       JOptionPane.INFORMATION_MESSAGE);
      } // end try
      catch(IOException ioe)
      {
         System.out.println("IO error:");
         ioe.printStackTrace();
         return;
      }
   } // end downloadLogs()
}
