# frozen_string_literal: true

require "cbor"
require "json"

require_relative "geo_code"

class GeoCodeRepo
	def initialize(memcache: MEMCACHE)
		@memcache = memcache
	end

	def find(q)
		cache(q) {
			EM::HttpRequest.new(
				"https://geocoder.ca/",
				tls: { verify_peer: true }
			).aget(query: { json: 1, locate: q }).then { |res|
				json = JSON.parse(res.response)
				raise "Geocode Failure" unless json["latt"] && json["longt"]

				json
			}
		}.then(&GeoCode.method(:for))
	end

protected

	def cache(k, &blk)
		k = "geocode_#{k.gsub(/ /, '%20')}"
		promise = EMPromise.new
		@memcache.get(k, &promise.method(:fulfill))
		promise.then { |cbor|
			CBOR.decode(cbor)
		}.catch(&blk).then { |result|
			@memcache.set(k, result.to_cbor)
			result
		}
	end
end
