package tcra.logger;

import java.io.BufferedReader;
import java.io.FileReader;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JPasswordField;
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.transport.IgnoreHostKeyVerification;

public class LogSubmitter
{
   private static LogSubmitter 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 LogSubmitter getInstance()
   {
      if(instance == null)
         instance = new LogSubmitter();
      return instance;
   } // end getInstance()
   
   private LogSubmitter() {}
   
   /**
    * Opens FTP connection to server listed in the config file and
    * uploads the user's tcra_log.
    */
   public void submitLog(JFrame frame, int source)
   {
      // check the log's ID
      String id = LogWriter.getInstance().getID();
      if(id.equals("BAD_LOG"))
      {
         JOptionPane.showMessageDialog(frame,
                     "tcra_log could not be found or is invalid",
                     "Log Error",
                     JOptionPane.ERROR_MESSAGE);
         return;
      } // end if
      
      // open SSH connection
      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(frame, "Connection Aborted");
            return;
         } // end else
         
         int result = ssh.authenticate(pwd);
         
         if(result == AuthenticationProtocolState.FAILED ||
            result == AuthenticationProtocolState.PARTIAL)
         {
            JOptionPane.showMessageDialog(frame, "Authentication Failed",
                                          "SFTP Failure",
                                          JOptionPane.ERROR_MESSAGE);
            ssh.disconnect();
            return;
         } // end if
         
         // Perform FTP actions over SSH connection
         SftpClient sftp = ssh.openSftpClient();
         sftp.cd(directory);
         sftp.mkdir("tcraLogs"); // only needs to happen once, but is safe multiple times
         sftp.put(System.getProperty("user.dir")+"/tcra_log", "tcraLogs/"+id+"_tcra_log");
         
         //cleanup
         sftp.quit();
         ssh.disconnect();
         
         JOptionPane.showMessageDialog(frame, "Log successfully uploaded");
      } // end try
      catch(java.io.IOException ioe)
      {
         System.out.println("Some error " + ioe);
         ioe.printStackTrace();
      } // end catch(IOException)
   } // end submitLog()
}
