class Nuntius::TwilioVoiceProvider

Send Voice call messages using twilio.com

def callback(params)

def callback(params)
  refresh.save
  twiml = script_for_path(message, "/#{params[:path]}", params)
  if twiml
    [200, {"Content-Type" => "application/xml"}, [twiml[:body]]]
  else
    [404, {"Content-Type" => "text/html; charset=utf-8"}, ["Not found"]]
  end
end

def callback_url

def callback_url
  Nuntius::Engine.routes.url_helpers.callback_url(message.id, host: host)
end

def client

def client
  @client ||= Twilio::REST::Client.new(sid, auth_token)
end

def deliver

def deliver
  # Need hostname here too
  response = client.calls.create(from: message.from.present? ? message.from : from, to: message.to, method: "POST", url: callback_url)
  message.provider_id = response.sid
  message.status = translated_status(response.status)
  message
end

def refresh

def refresh
  response = client.calls(message.provider_id).fetch
  message.provider_id = response.sid
  message.status = translated_status(response.status)
  message
end

def script_for_path(message, path = "/", _params)

def script_for_path(message, path = "/", _params)
  scripts = message.text.delete("\r").split("\n\n")
  scripts = scripts.map do |script|
    preamble = Preamble.parse(script)
    payload = preamble.metadata ? preamble.content : script
    payload = payload.gsub("{{url}}", callback_url)
    metadata = preamble.metadata || {path: "/"}
    {headers: metadata.with_indifferent_access, body: payload}
  end
  scripts.find { |s| s[:headers][:path] == path }
end