import Axios, { AxiosRequestConfig } from "axios";
import * as FormData from 'form-data';
import { Stream } from "stream";
const querystring = require('querystring');

/**
 * `http`/`get`
 */
export async function get<T = any>(url: string, config?: AxiosRequestConfig) {
    return (await Axios.get(url, config)).data as T;
}

/**
 * `http`/`post`
 */
export async function post<T = any>(url: string, data?: any, config?: AxiosRequestConfig) {
    return (await Axios.post(url, data, config)).data as T;
}

/**
 * `http`/`post`/`json`
 */
export async function postJson<T = any>(url: string, data?: any, config?: AxiosRequestConfig) {
    let headers = Object.assign(config?.headers || {}, { 'Content-Type': 'application/json;charset=utf-8' });
    return await post<T>(url, data, Object.assign(config || {}, { headers: headers }));
}

/**
 * `http`/`post`/`form`
 */
export async function postForm<T = any>(url: string,formdata?: any, data?: any, config?: AxiosRequestConfig) {
    let headers = Object.assign(config?.headers || {}, { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' });
    if(data && Object.keys(data).length > 0) {
        url = url + '?' + querystring.stringify(formdata);
    }
    return await post<T>(url, querystring.encode(data), Object.assign(config || {}, { headers: headers }));
}

/**
 * 上传文件?
 */
export async function postFile<T = any>(url: string, data: FormData, config?: AxiosRequestConfig) {
    let headers = Object.assign(config?.headers || {}, data.getHeaders());
    return await post<T>(url, data.getBuffer(), Object.assign(config || {}, { headers: headers }));
}

/**
 * 下载文件
 * 
 * ```
 * import { downloadFile } from "refs/nslib";
 * 
 * let buf = await downloadFile('https://image-cn.keytop.cn/452/172.19.2.6/2022/08/25/20220825143509132_172.19.2.6_024231.jpg');
 * ```
 * @throws {@link Error}
 */
export async function downloadFile(url: string, config?: AxiosRequestConfig) {
    return await get<Buffer>(url, Object.assign(config || {}, { responseType: 'arraybuffer' }));
}

/**
 * 下载文件
 * 
 * ```
 * import { downloadFileStream } from "refs/nslib";
 * 
 * let stream = await downloadFileStream('https://image-cn.keytop.cn/452/172.19.2.6/2022/08/25/20220825143509132_172.19.2.6_024231.jpg');
 * ```
 * @throws {@link Error}
 */
export async function downloadFileStream(url: string, config?: AxiosRequestConfig) {
    return await get<Stream>(url, Object.assign(config || {}, { responseType: 'stream' }));
}

/**
 * 下载文件并转`base64`
 * 
 * 下载失败则返回空字符串，不会抛出异常
 */
export async function downloadFile2Base64(url: string, config?: AxiosRequestConfig) {
    try {
        let buf = await downloadFile(url, config);
        return buf.toString('base64');
    } catch (error) {
        return '';
    }
}