import { GameState, isValidGameState } from "./types";

export class GameStateServerClient {
  _apiBaseUrl: string;
  constructor(apiBaseUrl: string) {
    this._apiBaseUrl = apiBaseUrl;
  }

  async saveState(id: string, gameState: GameState): Promise<boolean> {
    try {
      await fetch(this._apiBaseUrl + "/game/state/" + id, {
        method: "POST",
        mode: "cors",
        cache: "no-cache",
        credentials: "omit",
        headers: {
          "Content-Type": "application/json",
        },
        referrerPolicy: "no-referrer",
        body: JSON.stringify(gameState),
      });
      return true;
    } catch (saveStateToServerError) {
      console.error(
        "Failed to save state to server. The following info may help to solve this problem:",
        saveStateToServerError
      );
      return false;
    }
  }

  async loadState(id: string): Promise<GameState> {
    try {
      const rawResponse = await fetch(this._apiBaseUrl + "/game/state/" + id, {
        method: "GET",
        mode: "cors",
        cache: "no-cache",
        credentials: "omit",
        referrerPolicy: "no-referrer",
      });
      const decodedResponse = await rawResponse.json();
      if (!isValidGameState(decodedResponse)) {
        throw new TypeError("State from server is not a valid gameState");
      }
      return decodedResponse;
    } catch (loadGameStateFromServerError) {}
  }
}