package battleship;

import battleship.ship.IShip;

/**
 * Implementation of IDeployer with tight disposition, according to the rules.
 * 
 * @author Bernardo
 *
 */
public class TightDeployer implements IDeployer {

  @Override
  public IShip deployHorizontally(int xpos, int ypos, Fleet fleet, Territory territory) {
    if (xpos < 0 || ypos < 0) {
      return new NullShip();
    }
    if (xpos > territory.getWidth() - 1 || ypos > territory.getHeight() - 1) {
      return new NullShip();
    }
    IShip currentShip = fleet.getCurrentShip();
    if (!currentShip.isShip()) {
      return currentShip;
    }
    for (int ixpos = xpos; ixpos < xpos + currentShip.getLength(); ++ixpos) {
      if (!territory.isTightAvailable(ixpos, ypos)) {
        return new NullShip();
      }
    }
    fleet.next();
    return setHorizontally(currentShip, xpos, ypos, territory);
  }

  private IShip setHorizontally(IShip currentShip, int xpos, int ypos, Territory territory) {
    for (int ixpos = xpos; ixpos < xpos + currentShip.getLength(); ++ixpos) {
      territory.setShip(ixpos, ypos);
    }
    return currentShip;
  }

  private IShip setVertically(IShip currentShip, int xpos, int ypos, Territory territory) {
    for (int iypos = ypos; iypos < ypos + currentShip.getLength(); ++iypos) {
      territory.setShip(xpos, iypos);
    }
    return currentShip;
  }

  @Override
  public IShip deployVertically(int xpos, int ypos, Fleet fleet, Territory territory) {
    if (xpos < 0 || ypos < 0) {
      return new NullShip();
    }
    if (xpos > territory.getWidth() - 1 || ypos > territory.getHeight() - 1) {
      return new NullShip();
    }
    IShip currentShip = fleet.getCurrentShip();
    if (!currentShip.isShip()) {
      return currentShip;
    }
    for (int iypos = ypos; iypos < ypos + currentShip.getLength(); ++iypos) {
      if (!territory.isTightAvailable(xpos, iypos)) {
        return new NullShip();
      }
    }
    fleet.next();
    return setVertically(currentShip, xpos, ypos, territory);
  }


}
