import axios, { AxiosResponse } from "axios";
import { BASE, PING, PAGE, PONG } from "../const";

export class HttpClient {
  private _url: string;
  private _username: string | undefined;
  private _password: string | undefined;

  constructor(
    url: string,
    username: string | undefined,
    password: string | undefined
  ) {
    this._url = url;
    this._username = username;
    this._password = password;
  }

  async isConnected(): Promise<boolean> {
    var connected = false;
    if (await this.ping()) {
      connected = true;
      console.log("Connected to backend!");
    } else {
      connected = false;
      console.log("Connection failed backend!");
    }
    return connected;
  }

  private async ping(): Promise<string> {
    const response = await axios.get(`${BASE}${this._url}/${PING}`);
    return response.data;
  }

  private getAuthHeader() {
    return {
      Authorization: `Basic ${btoa(`${this._username}:${this._password}`)}`,
      "Content-Type": "application/json",
    };
  }

  async getValues(
    user: string,
    room: string,
    device: string
  ): Promise<AxiosResponse<any, any>> {
    const response = await axios.get(`${BASE}${this._url}/${PAGE}`, {
      headers: this.getAuthHeader(),
      params: {
        user: user,
        room: room,
        device: device,
      },
    });
    return response;
  }

  async newValue(
    user: string,
    room: string,
    device: string
  ): Promise<AxiosResponse<any, any>> {
    const response = await axios.post(
      `${BASE}${this._url}/${PAGE}`,
      {
        command: "MEASURE_NEW",
      },
      {
        headers: this.getAuthHeader(),
        params: {
          user: user,
          room: room,
          device: device,
        },
      }
    );
    return response;
  }
}
