# -----------------------------------------------------------------------
#  Copyright © 2012 ShepHertz Technologies Pvt Ltd. All rights reserved.
# -----------------------------------------------------------------------

require 'json'

class App42ResponseBuilder
  #      @param obj
  #      @param jsonObj
  #      @raise Exception
  def buildObjectFromJSONTree(obj,jsonObj)
    names = getNames(jsonObj)
    for name in names
      value = jsonObj[name]
      fieldName = "@"+name
      obj.instance_variable_set(:"#{fieldName}", value)
    end
  end

  #      @param serviceName
  #      @param json
  #      @return
  #      @raise Exception

  def getServiceJSONObject(serviceName,json)
    jsonObj = JSON.parse(json) rescue nil
    jsonObjApp42 = jsonObj["app42"]
    jsonObjResponse = jsonObjApp42["response"]
    jsonObjService = jsonObjResponse["#{serviceName}"]
    return jsonObjService;
  end

  #      @param json
  #      @return
  #      @raise Exception

  def isResponseSuccess(json)
    jsonObj = JSON.parse(json) rescue nil
    jsonObjApp42 = jsonObj["app42"]
    jsonObjResponse = jsonObjApp42["response"]
    return jsonObjResponse["success"]
  end

  def getNames(obj)
    names = []
    obj.each do |key, value|
      # puts"key is #{key}"  # key holds the key, value holds the value
      names.push(key)
    end
    return names
  end

  def getTotalRecords(json)
    totalRecords = -1;
    jsonObj = JSON.parse(json) rescue nil
    jsonObjApp42 = jsonObj["app42"]
    jsonObjResponse = jsonObjApp42["response"]
    if jsonObjResponse != nil && jsonObjResponse.key?("totalRecords")
      totalRecords = jsonObjResponse.fetch("totalRecords");
    end
    return totalRecords
  end

end