const request = require('request');
const express = require('express');

const { Cell } = require('../shared/enums.js');
const TicTacToe = require('../shared/tic-tac-toe.js');

const app = express();
const port = process.env.PORT || process.env.NODE_PORT || 1337;

const SERVER_URL = 'http://localhost:3000';

const postToServer = (route, gameState, callback) => {
  const requestOptions = {
    method: 'POST',
    url: `${SERVER_URL}${route}`,
  };

  if (gameState) {
    requestOptions.form = { gameState: JSON.stringify(gameState) };
  }

  // console.log(requestOptions);

  request(requestOptions, callback);
};

const parseGameState = body => JSON.parse(JSON.parse(body).gameState);

const makeMove = (gameState) => {
  const nextMove = TicTacToe.findBestMove(gameState, Cell.WHITE);
  console.log(nextMove);

  if (!nextMove) {
    console.log('game over D:');
    return;
  }

  postToServer('/makeMove', nextMove, (error, response, body) => {
    if (!JSON.parse(body).gameOver) {
      const newGameState = parseGameState(body);
      makeMove(newGameState);
    }
  });
};

app.listen(port, () => {
  console.log(`Client PI listening on port ${port}!`);

  postToServer('/startGame', null, (error, response, body) => {
    const gameState = parseGameState(body);
    console.log(gameState);

    makeMove(gameState);
  });
});

@@ -303,16 +303,440 @@
 3000';%0A%0A
+/**%0A * Helper function that wraps %60request%60. Provides full URL for a given route.%0A * Also format as the %60gameState%60 as a string if provided so that it can be%0A * sent in the body of the HTTP request.%0A *%0A * @param %7Bstring%7D route - The name of the route exposed by the server.%0A * @param %7Bnumber%5B%5D%5B%5D%7D gameState - The state of the Tic-Tac-Toe game.%0A * @param %7Bfunction%7D callback - Function to call once the request finishes.%0A */%0A
 const po
@@ -965,43 +965,8 @@
  %7D%0A%0A
-  // console.log(requestOptions);%0A%0A
   re
@@ -1006,79 +1006,421 @@
 %7D;%0A%0A
-const parseGameState = body =%3E JSON.parse(JSON.parse(body).gameState);%0A
+/**%0A * Converts string to gameState object.%0A *%0A * @param %7Bstring%7D body - The body of an HTTP response.%0A * @returns %7Bnumber%5B%5D%5B%5D%7D - The state of the Tic-Tac-Toe game.%0A */%0Aconst parseGameState = body =%3E JSON.parse(JSON.parse(body).gameState);%0A%0A/**%0A * Chooses best move given current state of the game, then sends that move%0A * to the sever.%0A *%0A * @param %7Bnumber%5B%5D%5B%5D%7D gameState - The state of the Tic-Tac-Toe game.%0A */
 %0Acon
@@ -1674,24 +1674,98 @@
  body) =%3E %7B%0A
+    // Continue making moves until the server responds that game is over.%0A
     if (!JSO
@@ -1885,16 +1885,133 @@
 %7D);%0A%7D;%0A%0A
+/**%0A * Entry point to the client application. Sends request to the server to%0A * start a new game of Tic-Tac-Toe.%0A */%0A
 app.list

Add comments to client/app.js