import { parseString } from "xml2js";
import https from "https";

/**
 * Perform an RSS/XML request
 */
export function rssRequest<T = any>(url: string) {
	return new Promise<T>((resolve, reject) => {
		https.get(url, { headers: { "User-Agent": "Node", "Accept": "application/rss+xml" } }, (response) => {
			if (response.statusCode !== 200) {
				reject("Status error: " + response.statusCode);
				return;
			}
			response.setEncoding("utf-8");
			let body = "";
			response.on("data", (chunk) => body += chunk);
			response.on("end", () => parseString(body, (err, result) => {
				if (err) {
					reject(err);
					return;
				}
				resolve(result);
			}));
		});
	});
}

/**
 * Perform a generic GET request
 */
 export function jsonRequest<T = any>(url: string) {
	return new Promise<T>((resolve, reject) => {
		https.get(url, { headers: { "User-Agent": "Node", "Accept": "*/*" } }, (response) => {
			if (response.statusCode !== 200) {
				reject("Status error: " + response.statusCode);
				return;
			}
			response.setEncoding("utf-8");
			let body = "";
			response.on("data", (chunk) => body += chunk);
			response.on("end", () => resolve(JSON.parse(body)));
		});
	});
}

/**
 * Perform a generic GET request
 */
 export function request(url: string, timeout: number = 10000) {
	return new Promise<string>((resolve, reject) => {
		https.get(url, { headers: { "User-Agent": "Node", "Accept": "*/*" }, timeout }, (response) => {
			if (response.statusCode !== 200) {
				reject("Status error: " + response.statusCode);
				return;
			}
			response.setEncoding("utf-8");
			let body = "";
			response.on("data", (chunk) => body += chunk);
			response.on("end", () => resolve(body));
		}).on("timeout", () => reject("timeout"));
	});
}

export function sleep(ms: number) {
	return new Promise(resolve => setTimeout(resolve, ms));
}

export function convertToBytes(size: number, unit: string, throwUnknownUnit: boolean = true) {
	switch(unit.toUpperCase()) {
		case "GB":
			return Math.ceil(size*1024*1024*1024);
		case "MB":
			return Math.ceil(size*1024*1024);
		case "KB":
			return Math.ceil(size*1024*1024);
		default:
			if (throwUnknownUnit) {
				throw new Error("Unknown unit provided");
			}
			return Math.ceil(size);
	}
}
