import {RemoteTask} from "./lib/RemoteTask";
import {commitDetailTask} from "./task-fn/executeDetail";
import {wait} from "gs-base";
import {isCache} from "./lib/cacheFetch";
import {executeSearchTask} from "./task-fn/executeSearchTask";
import {executeDetailTask} from "./task-fn/executeDetailTask";
import {executeBidTask} from "./task-fn/executeBidTask";
import {Db, ITask} from "/src-com";


export async function executeTask(reserve: boolean = false): Promise<any> {
	const task = await RemoteTask.get(reserve);
	const {type}: ITask = task || {};
	if (!type) {
		return {
			task,
			error: 'empty task'
		}
	}
	let cache: any, cached = false;
	try {
		if (type === 'detail') {
			(await isCache()) && (cache = await Db.detailCache.get(task.id));
			cached = !!cache;
			if (cache) {
				if (cache.detail) {
					cache.result = await commitDetailTask(task.id, [cache.detail]);
				} else if (cache.error) {
					cache.result = await commitDetailTask(task.id, [{error: cache.error}]);
				}
				return cache;
			}
			cache = await executeDetailTask(task as any);
			await Db.detailCache.set(task.id, cache);
			return cache;
		} else if (type === 'search') {
			return await executeSearchTask(task as any);
		} else if (type === 'bid' || type === 'buyItNow') {
			return await executeBidTask(task as any);
		}
	} catch (e) {
		console.log(e)
		throw e;
	} finally {
		await RemoteTask.end(task);
		if (!cached && type === 'detail' && !/^invalid id：/.test(cache?.error)) {
			console.log('--delay--');
			await wait(3, 6);
		}
	}
}


