ProviderBase = require './ProviderBase'
request = require 'request'
torify = require 'torify'
cheerio = require 'cheerio'
async = require 'async'

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

	ratings: (args, callback) ->
		jar = require('request').jar()
		async.waterfall [
			($next) =>
				torify
					url: 'http://www.metacritic.com/autosearch'
					jar: jar
					no_cache: true
					form:
						search_term: @data.title.replace(/\s/ig, '+')
					headers:
						'X-Requested-With': 'XMLHttpRequest'
						'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36'
						Referer: 'http://www.metacritic.com'
					method: 'POST'
				,$next
			,(res, body, $next) ->
				try 
					data = JSON.parse(body)

					torify 
						url: 'http://www.metacritic.com/' + data.autoComplete.shift().url
					,$next
				catch E
					$next null, null, null
			,(res, body, $next) ->
				add = {
					ratings: []
				}
				if body 
					$ = cheerio.load(body)

					add['ratings'].push
						source: 'Metascore'
						score: parseFloat($('[itemprop="ratingValue"]').text())

				$next null, add
		], callback



module.exports = Metacritic