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

/**
 * Perform an RSS/XML request
 */
export function rssRequest<T = any>(url: string, headers: {[key: string]: string} = {}) {
	return new Promise<[number|undefined, T]>((resolve, reject) => {
		https.get(url, { headers: { "User-Agent": "Autoplex", "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([response.statusCode, result]);
			}));
		});
	});
}

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

/**
 * Perform a generic GET request
 */
 export function request(url: string, timeout: number = 10000, headers: {[key: string]: string} = {}) {
	return new Promise<[number|undefined, string]>((resolve, reject) => {
		https.get(url, { headers: { "User-Agent": "Autoplex", "Accept": "*/*", ...headers }, 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([response.statusCode, body]));
		}).on("timeout", () => reject("timeout"));
	});
}

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);
	}
}
