# frozen_string_literal: true

require "delegate"
require "nokogiri"

class LocalCallingGuideRepo
	class Prefix < SimpleDelegator
		# @return [Float]
		def lat
			at("rc-lat").text.to_f
		end

		# @return [Float]
		def lon
			at("rc-lon").text.to_f
		end

		# @return [String]
		def region
			at("region").text
		end

		# @return [String]
		def locality
			at("rc").text
		end

		# @return [Hash<String, String>]
		def to_h
			{ "region" => region, "locality" => locality }
		end
	end

	# @param npa [String] area code (first 3 digits after country code)
	# @param nxx [String] exchange (digits 4-6)
	# @return [EMPromise<Prefix>]
	# @raise [RuntimeError] if no prefix data found
	def find(npa, nxx)
		EM::HttpRequest.new(
			"https://localcallingguide.com/xmlprefix.php",
			tls: { verify_peer: true }
		).aget(query: { npa: npa, nxx: nxx }).then { |res|
			prefix = Nokogiri::XML.parse(res.response).at("prefixdata")
			raise "No prefix data for #{npa}-#{nxx}" unless prefix

			Prefix.new(prefix)
		}
	end
end
