/* Utility functions for search results parser. */
function add(r,n,t){for(var e=[],u=Math.max(r.length,n.length),l=0,o=0;o<u||l;){var a,i=l+(o<r.length?r[o]:0)+(o<n.length?n[o]:0);e.push(i%t),l=Math.floor(i/t),o++}return e}function multiplyByNumber(r,n,t){if(r<0)return null;if(0==r)return[];for(var e=[],u=n;1&r&&(e=add(e,u,t)),0!=(r>>=1);)u=add(u,u,t);return e}function parseToDigitsArray(r,n){for(var t=r.split(""),e=[],u=t.length-1;u>=0;u--){var l=parseInt(t[u],n);if(isNaN(l))return null;e.push(l)}return e}function decToHex(r){var n=convertBase(r,10,16);return n?"0x"+n:null}function convertBase(r,n,t){var e=parseToDigitsArray(r,n);if(null===e)return null;for(var u=[],l=[1],o=0;o<e.length;o++)e[o]&&(u=add(u,multiplyByNumber(e[o],l,t),t)),l=multiplyByNumber(n,l,t);for(var a="",o=u.length-1;o>=0;o--)a+=u[o].toString(t);return a}function hexToDec(r){return"0x"===r.substring(0,2)&&(r=r.substring(2)),convertBase(r=r.toLowerCase(),16,10)}

const dataParser = (data) => {
	console.log(data);
	// const results = data[1]?.[0];

	// if (!results) {
	// 	console.log('No results in data.')
	// 	return null;
	// }

	const results = data;
	const outputs = [];

	for (const result of results) {
		const t = {};

		if (result === null || result.length === 0) {
			console.log('Empty result.')
			continue;
		}

		t['company_name'] = result[11];
		t['cid'] = hexToDec(result[10].split(':')?.[1]).toString();
		t['phone'] = result[178]?.[0][0];
		t['website'] = result[7]?.[1];
		if (t['website']) {
			t['website'] = 'https://' + t['website'];
		}

		t['review'] = result[4]?.[8];
		t['rating_count'] = result[4]?.[7];

		const addr = result[39];
		const cityAddr = result[18];

		if (addr) {
			t['address'] = addr.split('=').slice(-1)[0].replace(/\+/g, ' ');
		} else {
			t['address'] = cityAddr;
		}

		t['pincode'] = t['address'] ? t['address'].match(/\b[1000-999999]+\b/g) : "";
		t['pincode'] = t['pincode'] ? t['pincode'] : [];
		t['pincode'] = t['pincode'].length ? t['pincode'].pop() : "";
	

		t['category'] = result[13];
		t['city'] = cityAddr?.split(',')[0]?.trim();
		t['state'] = cityAddr?.split(',')[1]?.trim();
		t['country'] = cityAddr?.split(',').slice('-1')[0].trim();

		t['lat'] = result[9]?.[2];
		t['long'] = result[9]?.[3];

		outputs.push(t);
	}

	return outputs;
}
