let game = null;

export function create(fen) {
  game = new Chess(fen);
  return game;
}

export function get() { return game; }

export function move(from, to, promotion) {
  const m = game.move({ from, to, promotion: promotion || undefined });
  return m;
}

export function moveUci(uci) {
  const from = uci.substring(0, 2);
  const to = uci.substring(2, 4);
  const promotion = uci.length > 4 ? uci[4] : undefined;
  return move(from, to, promotion);
}

export function fen() { return game.fen(); }
export function turn() { return game.turn(); }
export function isGameOver() { return game.game_over ? game.game_over() : game.isGameOver(); }
export function isCheckmate() { return game.in_checkmate ? game.in_checkmate() : game.isCheckmate(); }
export function isDraw() { return game.in_draw ? game.in_draw() : game.isDraw(); }
export function isStalemate() { return game.in_stalemate ? game.in_stalemate() : game.isStalemate(); }
export function isCheck() { return game.in_check ? game.in_check() : game.isCheck(); }
export function isThreefoldRepetition() { return game.in_threefold_repetition ? game.in_threefold_repetition() : game.isThreefoldRepetition(); }
export function isInsufficientMaterial() { return game.insufficient_material ? game.insufficient_material() : game.isInsufficientMaterial(); }

export function legalMoves(square) {
  return game.moves({ square, verbose: true });
}

export function allMoves() {
  return game.moves({ verbose: true });
}

export function history() {
  return game.history({ verbose: true });
}

export function pgn() { return game.pgn(); }

export function reset() {
  game = new Chess();
  return game;
}

export function load(fen) {
  game.load(fen);
}

export function getResult(playerColor) {
  if (!isGameOver()) return null;
  if (isCheckmate()) {
    return turn() === playerColor ? 'loss' : 'win';
  }
  return 'draw';
}
