import {IPage, ISearchItem} from "/src-com";
import {parse} from 'node-html-parser';

export function parseProducts(docHtml: string): IPage<ISearchItem> {
	const map = new Map();
	const doc = parse(docHtml);
	doc.querySelectorAll('.Products__items .Product')
		.map(parseItem as any)
		.forEach(item => map.set(item.itemId, item));
	const total = parseInt(doc.querySelector('.Tab__item--current .Tab__subText').textContent?.replace(/\D+/g, ''))
	return {
		total: Math.max(total || 0, map.size),
		dataList: Array.from(map.values())
	};
}


function parseItem(el: HTMLElement): ISearchItem {
	return {
		itemId: el.querySelector('a.Product__imageLink')?.getAttribute('data-auction-id'),
		url: el.querySelector('a.Product__imageLink')?.getAttribute('href'),
		image: {
			imageUrl: el.querySelector('img.Product__imageData')?.getAttribute('src'),
			alt: el.querySelector('img.Product__imageData')?.getAttribute('alt'),
		},
		name: el.querySelector('.Product__title')?.textContent?.trim(),
		bid: el.querySelector('.Product__bid')?.textContent?.trim(),
		time: el.querySelector('.Product__time')?.textContent?.trim(),
		price: parseInt(el.querySelector('.Product__priceInfo .Product__priceValue')?.textContent?.replace(/\D+/g, '')),
		buyItNowPrice: parseInt(el.querySelectorAll('.Product__priceInfo .Product__priceValue')[1]?.textContent.replace(/\D+/g, '')) || -1,
		shippingFee: parseInt(el.querySelector('.Product__priceInfo .Product__postage')?.textContent?.replace(/\D+/g, '')) || 0,
	}
}

