require 'elasticsearch'
module JamRuby
  class ElasticSearch

    # index names
    MUSIC_SESSION_RATINGS = "music-session-ratings"

    def initialize()
      @log = Logging.logger[self]

      @client = Elasticsearch::Client.new(
          url: APP_CONFIG.elasticsearch_host,
          retry_on_failure: 2,
          request_timeout: 15,
          log: Rails.env.development?,
      )
    end

    def smash_indices

      index_settings = { number_of_shards: 1, number_of_replicas: 0 }
      settings = { settings: { index: index_settings } }

      @client.indices.delete(index: MUSIC_SESSION_RATINGS, body: settings)
      @client.indices.create(index: MUSIC_SESSION_RATINGS, body: settings)
    end

    def session_ratings(music_session, current_user, original_body)

      begin
        my_data = original_body.delete('**me')
        my_data["rating_type"] = original_body["rating_type"]
        my_data["comment"] = original_body["comment"]

        original_body.each do |k, other_data|
          begin
            # we init passwordfield as a UUID, which is a bogus hash; so if we see UUId, we know retailer has no password yet
            UUIDTools::UUID.parse(k)

            other_connection = Connection.find_by_client_id(k)
            if other_connection
              other_user = other_connection.user

              body = {me: my_data, other: other_data}

              body["@timestamp"] = Time.now.utc.iso8601
              body["my_email"] = current_user.email
              body["my_user_id"] = current_user.id
              body["other_email"] = other_user.email
              body["other_user_id"] = other_user.id
              body["music_session_id"] = music_session.id
              @client.index(id: "#{music_session.id}-#{current_user.id}-#{other_user.id}", index: MUSIC_SESSION_RATINGS, body: body)
            end
          rescue ArgumentError
            # that's ok ; there are non-uuid keys in here; we ignore those
          end
        end

        return true
      rescue => e
        @log.error("unable to parse session ratings #{e}")
        puts("unable to parse session ratings #{e}")
        return false
      end

    end

  end
end
