require 'net/http'
require 'json'

class Orion
  def initialize(base_url=nil)
    @@base_url = base_url if base_url
  end

  def statistics
    json_call = @@base_url + "statistics"
    begin
      result = get_url(json_call)
      if result.code == "200"
        JSON.parse(result.body)
      else
        nil
      end
    rescue
      nil
    end
  end
  # Orion.new().statistics

  def create_entity(type,id,attributes)
    json_call = @@base_url + "v1/updateContext"
    context = {}
    context['id'] = id
    context['type'] = type
    context['isPattern'] = "false"
    context['attributes'] = []
    context['attributes'] << attributes
    payload = {}
    payload['updateAction'] = "APPEND"
    payload['contextElements'] = []
    payload['contextElements'] << context
    begin
      result = post_url(json_call, payload.to_json)
      if result.code == "200"
        JSON.parse(result.body)['contextResponses'].first['statusCode']['code'] == "200"
      else
        nil
      end
    rescue
      nil
    end
  end

  def update_entity(type,id,attributes)
    create_entity(type,id,attributes)
  end
  # Orion.new()
  # Orion.new().create_entity("Request","Request 1",{"name":"like","type":"integer","value":"534"})

  def query_context(type,id,attributes=nil)
    json_call = @@base_url + "v1/queryContext"
    entity = {}
    entity['id'] = id
    entity['type'] = type
    entity['isPattern'] = "false"
    payload = {}
    payload['entities'] = []
    payload['entities'] << entity
    payload['attributes'] = attributes if attributes
    begin
      result = post_url(json_call, payload.to_json)
      if result.code == "200" and JSON.parse(result.body)['contextResponses'].first['statusCode']['code'] == "200"
        JSON.parse(result.body)['contextResponses'].first['contextElement']['attributes']
      else
        nil
      end
    rescue
      nil
    end
  end
  # Orion.new().query_context("Request","Request 1")
  # Orion.new().query_context("Request","Request 1","like")

private

  def get_url(url)
    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = false
    request = Net::HTTP::Get.new(uri.path, {'Content-Type' =>'application/json', 'Accept' => 'application/json'})
    http.request(request)
  end

  def post_url(url,data)
    uri = URI.parse(url)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = false
    request = Net::HTTP::Post.new(uri.path, {'Content-Type' =>'application/json', 'Accept' => 'application/json'})
    request.body = data
    http.request(request)
  end
end
