const routine = require('./routine')

const emptyBoard = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']

const textFromBoard = board =>
    ` ${board[0]} | ${board[1]} | ${board[2]} \n` +
    '-----------\n' +
    ` ${board[3]} | ${board[4]} | ${board[5]} \n` +
    '-----------\n' +
    ` ${board[6]} | ${board[7]} | ${board[8]}`

const numEmojis = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

const winningThrees = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],

  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],

  [0, 4, 8],
  [2, 4, 6]
]

const checkWinner = board => {
  for (const [a, b, c] of winningThrees) {
    if (board[a] !== ' ' && board[a] === board[b] && board[a] === board[c]) {
      return board[a]
    }
  }
  for (let i = 0; i < 9; i++) {
    if (board[i] === ' ') {
      return null
    }
  }
  return routine.tie
}

const getTurn = board => {
  let x = 0
  let o = 0
  board.forEach(spot => {
    if (spot === 'X') {
      x += 1
    } else if (spot === 'O') {
      o += 1
    }
  })
  return x > o ? 'O' : 'X'
}

const placeAt = (i, board, char) => {
  if (board[i] === ' ') {
    board[i] = char
    return true
  }
  return false
}

const applyTurn = (emoji, board) =>
  placeAt(numEmojis.indexOf(emoji), board, getTurn(board))

routine.build({
  startTriggers: ['ttt', 'tictactoe', 'tic-tac-toe'],
  initialBoard: () => emptyBoard,
  turnChoiceEmojis: ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'],
  gameName: 'Tic Tac Toe',
  textFromBoard,
  makeMove: applyTurn,
  checkWinner
})
