package seatrading.main;

import seatrading.ships.IShip;

/**
 * One thread, runs beside the main loop.
 *
 * @author Daniel "3ICE" Berezvai
 */
public class Simulation implements Runnable {

  public void run() {
    while (true) {
      for (IShip ship : SeaTrading.sea.ships) {
        if (ship.isAtHarbor()) {
          SeaTrading.profit -= ship.reFuel();
          if (ship.canTrade()) {
            SeaTrading.profit += ship.tradeAtHarbor();
          }
          Harbor nextHarbor = SeaTrading.rndHarbor();
          if (nextHarbor == ship.getHarbor()) {
            System.out.println(ship.getName() + " is being repaired at "
                    + ship.getHarbor().getName());
            while (nextHarbor == ship.getHarbor()) {
              nextHarbor = SeaTrading.rndHarbor();
            }
          }
          if (ship.setSailTo(nextHarbor)) {
            System.out.println(ship.getName() + " sets off on a journey to "
                    + nextHarbor.getName() + "...");
            ship.canTradeNextRound();
          } else {
            System.out.println("Sadly, " + ship.getName() + " can't get to " + nextHarbor.getName() + ".");
            ship.canNotTradeNextRound();
          }
        }// /*Spammy debug message*/ else {System.out.println(ship.getName() + " is still sailing.");}
      }
//      /*Use this to slow down the spam*/
//      try {
//        Thread.sleep(2000);
//      } catch (InterruptedException ex) {
//        System.err.println("I wasn't done yet!");
//      }
    }
  }
}
