const asyncHandler = require("express-async-handler");
const {ScraperTools} = require('../AuctionServices/Scraper/Scraper.js')
const Drouot = require('../AuctionServices/Scraper/Drouot/Drouot.js')
const Interencheres = require('../AuctionServices/Scraper/Interencheres/Interencheres.js')

let CleanUrl = function(url){
  
	if(String(url).split("http").length > 1){
		url = 'http'+String(url).split("http")[1]
	}else{
		url = ""
	}

	return url
}

let getAuctionPlatform = function(Url){
  
	let AuctionPlatform
	let STools = new ScraperTools();
  
	switch (STools.detectPlatform(Url)) {
  
	  case STools._CONST_INTERENCHERES:
		AuctionPlatform = new Interencheres(Url);
		break;
	  
	  case STools._CONST_DROUOT:
		AuctionPlatform = new Drouot(Url);
		break;
  
	  default:
		break;
	}
  
	return AuctionPlatform
}

// get Sale info
exports.sale = asyncHandler(async (req, res, next) => {

	let url = req.params.url	
	url = decodeURIComponent(url);
	
	url = CleanUrl(url)
	if(url == ""){
		res.status(400).send("URL not supported")
	}
	
	try{
		let AuctionPlatform = getAuctionPlatform(url);
		if(AuctionPlatform){

			console.log("Agent Follow Sale: ", url)

			switch(AuctionPlatform._BROWSER_TOOL){
				case "puppeteerBrowser":
					AuctionPlatform.Live(req.puppeteerBrowser)
					break;
				case "playwrightBrowser":
					AuctionPlatform.Live(req.playwrightBrowser)
					break;
			}
								
			res.status(200).send({"Following URL": url})
		}else{
			res.status(400).send("URL not supported")
		}
	}catch(e){
		res.status(500).send("Error: "+e)
	}		
});