# frozen_string_literal: true

require 'json'
require 'net/http'
require 'net/https'
require 'uri'
require 'rest-client'

class CdrSignalAPI
  def initialize(api_url, token)
    @token = token
    @last_update = 0
    @api = api_url
  end

  def parse_hash(hash)
    ret = {}
    hash.map do |k, v|
      ret[k] = CGI.encode(v.to_s.gsub('\\\'', '\''))
    end
    ret
  end

  def get(api)
    url = "#{@api}/bots/#{@token}/#{api}"
    JSON.parse(RestClient.get(url, { accept: :json }).body)
  end

  def post(api, params = {})
    url = "#{@api}/bots/#{@token}/#{api}"
    JSON.parse(RestClient.post(url, params, { accept: :json }).body)
  end

  def fetch_self
    get('')
  end

  def send_message(recipient, text, options = {})
    post('send', { phoneNumber: recipient.to_s, message: text }.merge(parse_hash(options)))
  end
end
