const Grid = require('./grid.js')
const Robot = require('./robot.js')
const { BLANK_SPACE, EMPTY_STRING, NEWLINE, ERRORS } = require('../utils')
/**
* Creates a new instance of Mars, a flat planet 😱
*/
class Mars {
/**
* Stores the instructions and accumulates robot's final instructions
* @param instructions {String} The instructions contains the grid's size and the robot's instructions
*/
constructor (instructions) {
if (instructions.length > 100) {
throw new Error(ERRORS.INSTRUCTIONS_NO_GREATER_100)
}
this.output = ''
this.instructions = instructions.split(NEWLINE)
}
/**
* Given some instructions, creates a Grid and sends all the robots to explore
* @returns {string} Indicates the final position and orientation of the robots in the grid and if they are lost
*/
sendRobots () {
console.log(this.instructions[0])
const [gridLength, gridHeight] = this.instructions[0].split(BLANK_SPACE)
console.log('Ancho', gridLength)
console.log('Altura: ', gridHeight)
console.log('...')
const grid = new Grid(gridHeight, gridLength)
let robot = new Robot(grid)
for (let i = 1; i < this.instructions.length; i++) {
const instruction = this.instructions[i]
// New Robot
if (this.isNewRobot(instruction)) {
robot = new Robot(grid)
}
// Robot Initial Position
else if (this.isRobotStartingPosition(instruction)) {
robot.setPosition(instruction)
}
// Move and save final position & orientation
else {
const move = robot.move(instruction)
this.output += (this.output.length > 0 ? NEWLINE : EMPTY_STRING) + move
}
}
return this.output
}
/**
* If the instruction is equal to empty string, creates a new robot which is going to be used
* in the next for-loop iteration
* @param instruction {String} The current instruction
* @returns {boolean}
*/
isNewRobot (instruction) {
return instruction === EMPTY_STRING
}
/**
* If the instruction includes a blank space, it means the instruction is the position where the robot should start the mission
* @param instruction {String} May be the starting position of a robot or the real instructions to follow to move
* @returns {Boolean}
*/
isRobotStartingPosition (instruction) {
return instruction.includes(BLANK_SPACE)
}
}
module.exports = Mars