export default class MainApi {
  private _url: string;
  constructor(url: string) {
    this._url = url;
  }

  _checkStatus(promise: Promise<any>) {
    return promise.then((res: any) => {
      if (res.ok) {
        return res.json();
      }
      console.log(res.text(), 'test')
      return Promise.reject(res.status);
    });
  }


  getRC() {
    const promise = fetch(`${this._url}/title/get`, {
      method: "GET",
    });
    return this._checkStatus(promise);
  }

  createSession(name: string) {
    const promise = fetch(`${this._url}/session/create`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        title: name,
      }),
    });
    return this._checkStatus(promise);
  }

  connectSession(code: any) {
    const promise = fetch(
      `${this._url}/session/connect?` +
      new URLSearchParams({ session_id: code }),
      {
        method: "GET",
      }
    );
    return this._checkStatus(promise);
  }
}
