package cap15.calcolatore;

import java.io.*;
import java.net.*;

public class CalcCliente
{ private String serverAddress;
  private int serverPort;
  private Socket s;
  private DataInputStream dis;
  private DataOutputStream dos;
  public CalcCliente(String h, int i) throws IOException
  { serverAddress = h;
    serverPort = i;
    s = new Socket(serverAddress, serverPort);
    dis = new DataInputStream(s.getInputStream());
    dos = new DataOutputStream(s.getOutputStream());
  }
  public CalcCliente() throws IOException
  { this("localhost", 10000);
  }
  public void uscita() throws IOException
  { dos.writeInt(Op.USCITA.toInt());
  }
  public int sum(int a, int b) throws IOException
  { dos.writeInt(Op.SOMMA.toInt());
    dos.writeInt(a);
    dos.writeInt(b);
    int r = dis.readInt();
    return r;
  }
  public int sub(int a, int b) throws IOException
  { dos.writeInt(Op.SOTTRAZIONE.toInt());
    dos.writeInt(a);
    dos.writeInt(b);
    int r = dis.readInt();
    return r;
  }
  public int mul(int a, int b) throws IOException
  { dos.writeInt(Op.MOLTIPLICAZIONE.toInt());
    dos.writeInt(a);
    dos.writeInt(b);
    int r = dis.readInt();
    return r;
  }
  public int div(int a, int b)
    throws IOException, ArithmeticException
  { dos.writeInt(Op.DIVISIONE.toInt());
    dos.writeInt(a);
    dos.writeInt(b);
    Op cond = Op.fromValue(dis.readInt());
    if (cond == Op.OK)
    { int r = dis.readInt();
      return r;
    }
    throw new ArithmeticException("Divisione per zero");
  }
}
