Request = require 'request'

class IpApiHandler
	lookup: (ip, callback) ->
		time = Date.now()

		Request.get "http://ip-api.com/json/#{ip}", (err, response, body) ->
			return callback(err) if err
			return callback('no response') if not body

			try
				data = JSON.parse(body)
			catch e
				return callback('could not parse json')

			callback(null, {
				country:
					name: data.country
					code: data.countryCode
				city: data.city
				region: data.regionName
			}, {
				source: 'ip-api'
				time: Date.now() - time
				ip: ip
			})

module.exports = new IpApiHandler