import {existsSync, mkdirSync, writeFileSync} from 'fs';
import * as path from 'node:path';
import {resolve, dirname} from 'path';
import {fileURLToPath} from 'url';

const DIR = resolve(dirname(fileURLToPath(import.meta.url)), '../data/icons');

export async function downloadIcon(icon, path) {
	if(!existsSync(DIR)) mkdirSync(dirname(path), {recursive: true});
	const res = await fetch(`https://openweathermap.org/img/wn/${icon}@2x.png`);
	const buf = Buffer.from(await res.arrayBuffer());
	writeFileSync(path, buf);
}

export async function fetchIcon(icon) {
	const iconPath = path.join(DIR, icon + '.png');
	if(!existsSync(DIR) || !existsSync(iconPath))
		await downloadIcon(icon, iconPath);
	return iconPath;
}
