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

require 'connection/RESTConnection'
require 'App42_Ruby_API/App42ResponseBuilder'
require 'util/util'
require 'json'

module App42
  module Session

    #
    #
    # SessionResponseBuilder class converts the JSON response retrieved from the
    # server to the value object i.e Session
    #
    #
    class SessionResponseBuilder < App42ResponseBuilder

      #
      # Converts the response in JSON format to the value object i.e Session
      #
      # @param json
      #      - response in JSON format
      #
      # @return Session object filled with json data
      #
      #
      def buildSessionResponse(json)
        sessionObj = Session.new
        attributeList = Array.new()
        sessionObj.attributeList = attributeList
        sessionObj.strResponse = json
        jsonObj = JSON.parse(json)
        jsonObjApp42 = jsonObj.fetch("app42")
        jsonObjResponse = jsonObjApp42.fetch("response")
        sessionObj.isResponseSuccess=(jsonObjResponse.fetch("success"))
        jsonObjSession = jsonObjResponse.fetch("session")

        buildObjectFromJSONTree(sessionObj,jsonObjSession)

        if jsonObjSession.has_key?("attributes") == false
          return sessionObj
        end

        jsonObjAttributes = jsonObjSession.fetch("attributes")

        if jsonObjAttributes.has_key?("attribute") == false
          return sessionObj
        end
        if jsonObjAttributes["attribute"].instance_of?(Hash)
          # Only One attribute is there
          jsonObjAttribute = jsonObjAttributes.fetch("attribute")
          attribute = App42::Session::Attribute.new(sessionObj)
          buildObjectFromJSONTree(attribute,jsonObjAttribute)
        else
          jsonObjAttributeArray = jsonObjAttributes.fetch("attribute")
          jsonObjAttributeArray.length.times do |i|
            # Get Individual Attribute Node and set it into Object
            jsonObjAttribute = jsonObjAttributeArray[i]
            attribute = App42::Session::Attribute.new(sessionObj)
            buildObjectFromJSONTree(attribute,jsonObjAttribute)
          end
        end
        return sessionObj
      end
    end
  end
end