var states = new Array();

function getNextGameId () {
  return states.length == 0 ? 0 : states.map(function (s) { return s.gameId; }).reduce((prev, curr) => prev > curr ? prev : curr) + 1;
}

function doesGameExists (gameId) {
  return states.some(function (s) { return s.gameId == gameId; });
}

exports.createGameState = function (placementOfWinner, winningItem, losingItem) {
  var state = {
          gameId: getNextGameId(),
          status: 'unselected',
          outcome: 'unknown',
          initialSelection: undefined,
          finalSelection: undefined,
          probabilityOfWinning: undefined,
          userSwitchedSelection: undefined,
          winner: placementOfWinner,
          doors: [  {placement: 0, opened: false, content: losingItem, selected: false},
                    {placement: 1, opened: false, content: losingItem, selected: false},
                    {placement: 2, opened: false, content: losingItem, selected: false} ]
          };
  // set the car
  state.doors.map(function (s) { if (s.placement == placementOfWinner) s.content = winningItem; });
  save(state);

  return state.gameId;
}

exports.getGameState = function (gameId) {
  return states.filter(function(s) { return s.gameId == gameId; })[0];
};

function save (state) {
  states[state.gameId] = state;
}
exports.saveGameState = save;