ProviderBase = require './ProviderBase'
torify = require 'torify'
async = require 'async'
cheerio = require 'cheerio'
_ = require 'underscore'

class PriceCharting extends ProviderBase
	constructor: (@data) ->

	prices: (args, callback) ->
		additonal = {}
		additonal['prices'] = []
		torify 
			timeout: (1000 * 10)
			url: 'http://videogames.pricecharting.com/search'
			qs: 
				q: (@data.title or @data.game_name)
				submit: 'Go'
		,(E, res, body) =>
			$ = cheerio.load body or ""
			torify
				timeout: (1000 * 10)
				url: 'http://videogames.pricecharting.com' + $('#games_table').find('.title > a').first().attr('href')
			,(E, res, body) =>
				$ = cheerio.load body or ""
				prices = {}
				async.each $('tr[data-source-id]'), (ele, next) =>
					if ($(ele).find('.price').text().trim().replace(/[^0-9-.]/g, ''))
						prices[$(ele).find('.store').text().trim()] = parseFloat($(ele).find('.price').text().trim().replace(/[^0-9-.]/g, ''))
					next()
				,(E) =>
					_.each prices, (v, k) =>
						additonal['prices'].push({
							store: k,
							price: v
						})

					callback null, additonal

module.exports = PriceCharting