////////////////////////////////////////
// Programming project code
// UniBw M, 2022, 2023, 2024
// www.unibw.de/inf2
// (c) Mark Minas (mark.minas@unibw.de)
////////////////////////////////////////

package pp.battleship.game.client;

import pp.battleship.message.server.GameDetails;
import pp.battleship.model.Battleship;
import pp.battleship.model.Rotation;

import java.util.Map.Entry;

/**
 * Represents the state of the client waiting for the
 * {@linkplain pp.battleship.message.server.GameDetails}
 * from the server.
 */
class InitialState extends ClientState {
    /**
     * Creates a new initial state.
     *
     * @param logic the game logic
     */
    public InitialState(ClientGameLogic logic) {
        super(logic);
    }

    /**
     * Sets the game details provided by the server.
     *
     * @param details the game details including map size and ships
     */
    @Override
    public void receivedGameDetails(GameDetails details) {
        logic.initializeMaps(details);
        fillHarbor(details);
        logic.setInfoText(details.getInfoTextKey());
        logic.setState(new EditorState(logic));
    }

    /**
     * Fills the harbor with ships as specified by the game details.
     *
     * @param details the game details including map size and ships
     */
    private void fillHarbor(GameDetails details) {
        int y = 0;
        for (Entry<Integer, Integer> entry : details.getShipNums().entrySet()) {
            final int len = entry.getKey();
            final int num = entry.getValue();
            for (int i = 0; i < num; i++) {
                final Battleship ship = new Battleship(len, 0, y++, Rotation.RIGHT);
                logic.getHarbor().add(ship);
            }
        }
    }

    @Override
    public boolean maySaveMap() {
        return false;
    }
}
