# frozen_string_literal: true

require "uri"

class CustomerFwd
	def self.for(uri, timeout)
		timeout = Timeout.new(timeout)
		return if !uri || timeout.zero?
		URIS.fetch(uri.split(":", 2).first.to_sym) {
			raise "Unknown forward URI: #{uri}"
		}.new(uri, timeout)
	end

	class Timeout
		def initialize(s)
			@timeout = s.nil? || s.to_i.negative? ? 300 : s.to_i
		end

		def zero?
			@timeout.zero?
		end

		def to_i
			@timeout
		end
	end

	def create_call_request
		request = Bandwidth::ApiCreateCallRequest.new.tap do |cc|
			cc.to = to
			cc.call_timeout = timeout.to_i
		end
		yield request if block_given?
		request
	end

	class Tel < CustomerFwd
		attr_reader :timeout

		def initialize(uri, timeout)
			@tel = uri.sub(/^tel:/, "")
			@timeout = timeout
		end

		def to
			@tel
		end
	end

	class SIP < CustomerFwd
		attr_reader :timeout

		def initialize(uri, timeout)
			@uri = uri
			@timeout = timeout
		end

		def to
			@uri
		end
	end

	class XMPP < CustomerFwd
		attr_reader :timeout

		def initialize(uri, timeout)
			@jid = uri.sub(/^xmpp:/, "")
			@timeout = timeout
		end

		def to
			"sip:#{ERB::Util.url_encode(@jid)}@sip.cheogram.com"
		end
	end

	URIS = {
		tel: Tel,
		sip: SIP,
		xmpp: XMPP
	}.freeze
end
