import axios, { AxiosInstance, AxiosRequestConfig } from "axios";
import http from "http";
import https from "https";
import { Stream } from "stream";

export default class HttpUtil {
  private static axiosInstance: AxiosInstance = axios.create({
    httpAgent: new http.Agent({ timeout: 10000 }),
    httpsAgent: new https.Agent({ timeout: 10000 }),
  });

  static async get<T = any>(
    url: string,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return (await this.axiosInstance.get(url, config)).data;
  }

  static async post<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return (await this.axiosInstance.post(url, data, config)).data;
  }

  static async put<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return (await this.axiosInstance.put(url, data, config)).data;
  }

  static async patch<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return (await this.axiosInstance.patch(url, data, config)).data;
  }

  static async delete<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return (await this.axiosInstance.delete(url, config)).data;
  }

  static async getBuffer(url: string, config?: AxiosRequestConfig) {
    return await this.get<Buffer>(
      url,
      Object.assign(config || {}, { responseType: "arraybuffer" })
    );
  }

  static async getStream(url: string, config?: AxiosRequestConfig) {
    return await this.get<Stream>(
      url,
      Object.assign(config || {}, { responseType: "stream" })
    );
  }
}