package com.marinilli.b2.c6.bank;

import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.io.*;
import java.net.MalformedURLException;
import java.net.Socket;

/**
 * Chapter 6 - This class encapsulates business-related utility services
 *
 * @author Mauro Marinilli
 * @version 1.0
 */

public class BankClientManager {
  private String[] arguments;
  private Socket socket = null;
  private DataOutputStream out = null;
  private DataInputStream in = null;
  private String thisClientId;

  /**
   * Class constructor
   *
   */
  public BankClientManager() {
    try {
      socket = new Socket("localhost", 3333);
      out = new DataOutputStream(socket.getOutputStream());
      in = new DataInputStream(socket.getInputStream());
    } catch (Exception e) {
      System.out.println("BankClientManager()- Couldn't work out the connection: "+e);
      System.exit(1);
    }
    System.out.println("BankClientManager() - Connectiom established.");
  }

  /**
   * implements the POST Command
   */
  public void post(String data) throws IOException{
    sendCommand('p');
    out.writeUTF(data);
  }

  /**
   * implements the QUIT Command
   */
  public void quit() throws IOException{
    sendCommand('q');
    out.close();
    in.close();
    socket.close();
  }

  /**
   * implements the GET Command
   */
  public byte[] get(String serverFilename) throws IOException{
    sendCommand('g');
    out.writeUTF(serverFilename);
    int size = in.readInt();
    byte[] b = new byte[size];
    in.readFully(b);
    return b;
  }

  /**
   * sends a command to the server
   */
  private void sendCommand(char c){
    try {
      out.writeChar(c);
      System.out.println("BankClientManager- send command "+c);
    } catch (IOException exce) {
      System.out.println("BankClientManager- sendCommand()"+exce);
    }
  }

}