package WheelOfFortune.webMonitor;


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;


public class WebMonitorInput {
 private WebMonitor wm;
 private WebMonitorOutput out;

 public WebMonitorInput(WebMonitor wm, WebMonitorOutput out) {
  this.wm = wm;
  this.out = out;
 
  out.getConnectBtn().addActionListener(new PuzzleListener());
  out.getDisconnectBtn().addActionListener(new PuzzleListener());
  out.getRefreshRemoteBtn().addActionListener(new PuzzleListener());
  out.getViewBtn().addActionListener(new PuzzleListener());
  out.getApproveBtn().addActionListener(new PuzzleListener());
  out.getRejectBtn().addActionListener(new PuzzleListener());
 }

 private void viewFile() {
  int i = out.getRemoteList().getSelectedIndex();

  if(i == -1) {
   return;
  }
  wm.viewFile(i);
 }

 private class PuzzleListener implements ActionListener {
  public void actionPerformed(ActionEvent ae) {

   if(ae.getSource().equals(out.getConnectBtn())) {
    Runnable r = new Runnable() {
     public void run() {
      String address = out.getAddressFld().getText();

      int port = 0;

      try {
       port = Integer.parseInt(out.getPortFld().getText());
      } catch(NumberFormatException nfe) {
       out.printErrorMessage("Invalid port number.");
       return;
      }

      String userName = out.getUserNameFld().getText();
      String pass = new String(out.getPasswordFld().getPassword());

      wm.connect(address, port, userName, pass);
     }
    };

    new Thread(r).start();
   }
   else if(ae.getSource().equals(out.getDisconnectBtn())) {
    Runnable r = new Runnable() {
     public void run() {
      wm.disconnect();
     }

    };

    new Thread(r).start();
   }
   else if(ae.getSource().equals(out.getRefreshRemoteBtn())) {
    Runnable r = new Runnable() {
     public void run() {
      wm.refreshRemoteList();
     }
    };

    new Thread(r).start();
   }

   else if(ae.getSource().equals(out.getViewBtn())) {
    Runnable r = new Runnable() {
     public void run() {
      viewFile();
     }
    };

    new Thread(r).start();
   }
   else if(ae.getSource().equals(out.getApproveBtn())) {
    Runnable r = new Runnable() {
     public void run() {
      wm.approve();
     }
    };

    new Thread(r).start();
   }
   
   else if(ae.getSource().equals(out.getRejectBtn())) {
    Runnable r = new Runnable() {
     public void run() {
      wm.reject();
     }
    };

    new Thread(r).start();
  
   }
  }
 }
}
