/*
 * Copyright (C) 2022 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

import {Requestor} from '@openid/appauth';
import {CapacitorHttp, HttpHeaders, HttpResponse} from '@capacitor/core';
import {XhrSettings} from 'ionic-appauth/lib/cordova';

// 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 CapacitorHttp.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 CapacitorHttp.post({
      url,
      data,
      headers,
    }).then((response: HttpResponse) => {
      return response.data as T;
    });
  }

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

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