import ReactNativeBlobUtil from "react-native-blob-util";

export async function downloadLatestApk(serverIp: string, port: string) {
	const url = `http://${serverIp}:${port}/lst/api/mobile/apk/latest`;

	const apkPath = `${ReactNativeBlobUtil.fs.dirs.DownloadDir}/lst-mobile.apk`;

	// delete old apk if it exists
	const exists = await ReactNativeBlobUtil.fs.exists(apkPath);

	if (exists) {
		const stat = await ReactNativeBlobUtil.fs.stat(apkPath);

		// last modified time
		const lastModified = Number(stat.lastModified);

		// current time
		const now = Date.now();

		// 5 minutes in ms
		const fiveMinutes = 5 * 60 * 1000;

		// skip download if file is fresh
		if (now - lastModified < fiveMinutes) {
			console.log("APK already downloaded recently, skipping.");

			return {
				skipped: true,
				path: apkPath,
			};
		}

		// delete old apk before redownload
		await ReactNativeBlobUtil.fs.unlink(apkPath);
	}

	const res = await ReactNativeBlobUtil.config({
		addAndroidDownloads: {
			useDownloadManager: true,
			notification: true,
			title: "LST Mobile Update",
			description: "Downloading update for StageNow install",
			mime: "application/vnd.android.package-archive",
			path: apkPath,
			mediaScannable: true,
		},
	}).fetch("GET", url);

	return res.path();
}
