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

public class Grocery{
    
  public static void main(String[] args) throws IOException {
    int port = 0;
    try {
      port = Integer.parseInt(args[0]);
      int seed = 1002;
      if (args.length > 2) seed = Integer.parseInt(args[1]);
      ServerSocket serverSocket = null;
            
      boolean listening = true;
      serverSocket = new ServerSocket(port); 
            
      while (listening)
        new GroceryThread(serverSocket.accept(), seed).start();
      serverSocket.close();

    } catch (IOException e) {
      System.err.println("Could not listen on port: " +port);
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Usage: java Grocery <port> [optional seed]");
    }
  }
}

class GroceryThread extends Thread{
  private Socket socket = null;
  private Random random = null;
  private int antal = 0;
  
  public GroceryThread(Socket socket, long seed) {
    super("GroceryThread");
    this.socket = socket;
    this.random = new Random(seed);
  }

  public void run(){
    PrintWriter out;
    BufferedReader in;
    try{
      out = new PrintWriter(socket.getOutputStream(), true);
      in  = new BufferedReader
        (new InputStreamReader
         (socket.getInputStream()));

      boolean forever = true;
      while (forever) {
        String order = in.readLine();
        String [] ovek = order.split(" ", 2);
        int nr = Integer.parseInt(ovek[0]);
        antal += nr;
        
        // tar 1-4 sekunder att expediera
        this.sleep(1000 * (random.nextInt(3) + 1));

        out.print(nr);
        out.println(" majskyckling");
        System.out.print(nr);
        System.out.println(" majskyckling   totalt " + antal);
      }
      out.close();
      in.close();
      socket.close();
      
    }catch (IOException e){
      e.printStackTrace();
    }catch (InterruptedException e){
      e.printStackTrace();
    }
  }
}
