/*
 * Copyright (C) 2023 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 {Injectable} from '@angular/core';
import {Requestor} from '@openid/appauth';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {XhrSettings} from 'ionic-appauth/lib/cordova';
import {firstValueFrom, Observable} from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class NgHttpService implements Requestor {
  constructor(private http: HttpClient) {}

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

    let observable: Observable<T>;

    switch (settings.method) {
      case 'GET': {
        observable = this.http.get<T>(settings.url, {
          headers: this.getHeaders(settings.headers),
        });
        break;
      }
      case 'POST': {
        observable = this.http.post<T>(settings.url, settings.data, {
          headers: this.getHeaders(settings.headers),
        });
        break;
      }
      case 'PUT': {
        observable = this.http.put<T>(settings.url, settings.data, {
          headers: this.getHeaders(settings.headers),
        });
        break;
      }
      case 'DELETE': {
        observable = this.http.delete<T>(settings.url, {
          headers: this.getHeaders(settings.headers),
        });
        break;
      }
    }

    return firstValueFrom(observable);
  }

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  private getHeaders(headers: any): HttpHeaders {
    let httpHeaders: HttpHeaders = new HttpHeaders();

    if (headers !== undefined) {
      for (const key of Object.keys(headers)) {
        httpHeaders = httpHeaders.append(key, headers[key]);
      }
    }

    return httpHeaders;
  }
}
