package cap15.calcolatore;

import java.io.*;
import java.net.*;

public class CalcServitore
{ private final int port;
  private DataInputStream dis;
  private DataOutputStream dos;
  CalcServitore(int p)
  { port = p;
  }
  CalcServitore()
  { this(10000);
  }
  public void startService()
  { ServerSocket serv = null;
    try
    { serv = new ServerSocket(port);
    }
    catch (IOException ioe)
    { System.out.println(
        "Non riesco a mettermi in ascolto sulla porta specificata");
      System.exit(1);
    }
    while (true)
    { try
      { Socket s = serv.accept();
        System.out.println("Si e' connesso un cliente");
        dis = new DataInputStream(s.getInputStream());
        dos = new DataOutputStream(s.getOutputStream());
        Op op;
        boolean continua = true;
        while (continua)
        { op = Op.fromValue(dis.readInt());
          switch (op)
          { case SOMMA:
              somma();
              break;
            case SOTTRAZIONE:
              sottrazione();
              break;
            case DIVISIONE:
              divisione();
              break;
            case MOLTIPLICAZIONE:
              moltiplicazione();
              break;
            case USCITA:
              continua = false;
              break;
          }
        }
      }
      catch (IOException ioe)
      { System.out.println(
          "Problemi durante la comunicazione: " +
          ioe.getMessage());
      }
      finally
      { try
        { if (dis != null)
            dis.close();
          if (dos != null)
            dos.close();
        }
        catch (IOException ioe) {}
      }
    }
  }
  private void somma() throws IOException
  { int a = dis.readInt();
    int b = dis.readInt();
    int r = a + b;
    dos.writeInt(r);
  }
  private void sottrazione() throws IOException
  { int a = dis.readInt();
    int b = dis.readInt();
    int r = a - b;
    dos.writeInt(r);
  }
  private void divisione() throws IOException
  { int a = dis.readInt();
    int b = dis.readInt();
    int r;
    try
    { r = a / b;
    }
    catch (ArithmeticException e)
    { dos.writeInt(Op.ERROR.toInt());
      return;
    }
    dos.writeInt(Op.OK.toInt());
    dos.writeInt(r);
  }
  private void moltiplicazione() throws IOException
  { int a = dis.readInt();
    int b = dis.readInt();
    int r = a * b;
    dos.writeInt(r);
  }
  public static void main(String[] args)
  { CalcServitore s;
    if (args.length == 0)
      s = new CalcServitore();
    else
      s = new CalcServitore(Integer.parseInt(args[0]));
    s.startService();
  }
}
