import {Requestor} from '@openid/appauth';
import {Http, HttpHeaders, HttpResponse} from '@capacitor-community/http';
import {XhrSettings} from 'ionic-appauth/lib/cordova';
import qs from 'qs';

// REQUIRES CAPACITOR PLUGIN
// @capacitor-community/http
export class CapacitorRequestor extends Requestor {
  constructor() {
    super();
  }

  public async xhr<T>(settings: XhrSettings): Promise<T> {
    if (!settings.method) settings.method = 'GET';

    switch (settings.method) {
      case 'GET':
        return this.get(settings.url, settings.headers);
      case 'POST':
        return this.post(settings.url, settings.data, settings.headers);
      case 'PUT':
        return this.put(settings.url, settings.data, settings.headers);
      case 'DELETE':
        return this.delete(settings.url, settings.headers);
    }
  }

  private async get<T>(url: string, headers: HttpHeaders) {
    return Http.get({url, headers}).then(
      (response: HttpResponse) => response.data as T,
    );
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private async post<T>(url: string, data: any, headers: HttpHeaders) {
    return Http.post({url, data: qs.parse(data), headers}).then(
      (response: HttpResponse) => response.data as T,
    );
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private async put<T>(url: string, data: any, headers: HttpHeaders) {
    return Http.put({url, data, headers}).then(
      (response: HttpResponse) => response.data as T,
    );
  }

  private async delete<T>(url: string, headers: HttpHeaders) {
    return Http.del({url, headers}).then(
      (response: HttpResponse) => response.data as T,
    );
  }
}
