package com.marinilli.b2.c6.bank;

import java.io.*;
import java.net.*;

/**
 * Chapter 6 - The old BankClient
 *
 * @author Mauro Marinilli
 * @version 1.0
 */

public class OldBankClient {
  Socket socket = null;
  DataOutputStream out = null;
  DataInputStream in = null;
  private String thisClientId;

  public OldBankClient() {
    thisClientId = "client0";
    try {
      socket = new Socket("localhost", 3333);
      out = new DataOutputStream(socket.getOutputStream());
      in = new DataInputStream(socket.getInputStream());
    } catch (Exception e) {
      System.out.println("BankClient- Couldn't work out the connection: "+e);
      System.exit(1);
    }
    try {
      executeTransaction();

      // dismiss connection
      sendCommand('q');
      out.close();
      in.close();
      socket.close();
    } catch (IOException exce) {
      System.out.println("BankClient- executing transaction: "+exce);
    }
    System.out.println("BankClient- Client Log out.");
  }

  private void post(String data) throws IOException{
    sendCommand('p');
    out.writeUTF(data);
  }

  private 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;
  }

  private void executeTransaction() throws IOException{
    byte[] b = get("test.txt");
    post("hello everybody");
  }

  private void sendCommand(char c){
    try {
      out.writeChar(c);
      System.out.println("BankClient: send command "+c);
    } catch (IOException exce) {
      System.out.println("BankClient- "+exce);
    }
  }

  private void cache(String name, byte[] b) {
    try {
      FileOutputStream fos = new FileOutputStream("cached/"+name);
      fos.write(b);
      fos.close();
    } catch (IOException exce) {
      System.out.println("BankClient- cache("+name+") "+exce);
    }
  }

  public static void main(String[] args) throws IOException {
    OldBankClient c = new OldBankClient();
  }

}