package WheelOfFortune.puzzleManager;

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


public class PuzzleManagerInput {
 private PuzzleManager pm;
 private PuzzleManagerOutput out;

 public PuzzleManagerInput(PuzzleManager pm, PuzzleManagerOutput out) {
  this.pm = pm;
  this.out = out;


  out.getConnectBtn().addActionListener(new PuzzleListener());
  out.getDisconnectBtn().addActionListener(new PuzzleListener());
  out.getRefreshLocalBtn().addActionListener(new PuzzleListener());
  out.getRefreshRemoteBtn().addActionListener(new PuzzleListener());
  out.getUploadBtn().addActionListener(new PuzzleListener());
  out.getDownloadBtn().addActionListener(new PuzzleListener());
 }

 private void uploadSelected() {
  int[] indices = out.getLocalList().getSelectedIndices();
  for(int i = 0;i < indices.length;++i) {
  pm.uploadFile(indices[i]);
  }
 }

 private void downloadSelected() {
  int[] indices = out.getRemoteList().getSelectedIndices();
  for(int i = 0;i < indices.length;++i) {
  pm.downloadFile(indices[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());


      pm.connect(address, port, userName, pass);
     }
    };
    new Thread(r).start();
   }
   else if(ae.getSource().equals(out.getDisconnectBtn())) {
   	Runnable r = new Runnable() {
	 public void run() {
       pm.disconnect();
     }
    };
    new Thread(r).start();
   }
   
   else if(ae.getSource().equals(out.getRefreshLocalBtn())) {
  	Runnable r = new Runnable() {
	 public void run() {
      pm.refreshLocalList();
     }
    };
   new Thread(r).start();
   }
   
   else if(ae.getSource().equals(out.getRefreshRemoteBtn())) {
     	Runnable r = new Runnable() {
	 public void run() {
         pm.refreshRemoteList();
     }
    };
   new Thread(r).start();
   }
   
   else if(ae.getSource().equals(out.getUploadBtn())) {
    Runnable r = new Runnable() {
	 public void run() {
      uploadSelected();
     }
    };
   new Thread(r).start();
   }
   
   else if(ae.getSource().equals(out.getDownloadBtn())) {
    Runnable r = new Runnable() {
	 public void run() {
         downloadSelected();
     }
    };
   new Thread(r).start();

   }
  }
 }
}