require 'will_paginate/array'
require 'will_paginate/collection'

begin
  require 'cubert/client'
rescue LoadError
  (Rails.configuration.cubert.server ||= {}).store(:enabled, false)
end

class CubertRequestLogsService
  DEFAULT_TTL = "7d"

  delegate :enabled?, :disabled?, to: 'self.class'

  class << self

    def disabled?
      !enabled?
    end

    def enabled?
      config[:enabled]
    end

    def config
      Rails.configuration.cubert.server or {}
    end

    def enable(service_id, opts = {})
      return false if disabled?

      default_opts = { retention: { ttl: DEFAULT_TTL } }
      bucket_id = connection.create_bucket(default_opts.merge(opts)).id

      ServiceCubertInfo.create! service_id: service_id, bucket_id: bucket_id
      ThreeScale::Core::Service.set_log_bucket service_id, bucket_id
    end

    def disable(service_id)
      return false if disabled?

      ServiceCubertInfo.where(service_id: service_id).first.destroy
      ThreeScale::Core::Service.clear_log_bucket service_id
    end

    private

    def connection
      new(nil).connection
    end
  end

  def initialize(cubert_info)
    @cubert_info = cubert_info
  end

  def get_list(search_options = {}, pagination_options = {})
    return empty_collection if !@cubert_info || disabled?

    search_options[:service_id] = @cubert_info.service_id.to_s

    documents = connection.filter_documents(
      search_options,
      bucket_id,
      collection,
      pagination_options,
    )

    paginate(
      RequestLogCollection.new(@cubert_info.service, documents),
      pagination_options[:page] || 1,
      pagination_options[:per_page] || 20,
    )
  end

  def store_logs(*logs)
    return false if disabled?
    logs.flatten.each do |log|
      connection.create_document({
        body: log, bucket: bucket_id, collection: collection
      })
    end
  end

  def connection
    @connection ||= Cubert::Client::Connection.new(server)
  end

  private

  def paginate(collection, page, per_page)
    WillPaginate::Collection.create(page, per_page, collection.total) do |pager|
      pager.replace(collection.logs)
    end
  end

  def empty_collection
    [].paginate
  end

  def bucket_id
    @cubert_info.bucket_id
  end

  def collection
    'request_logs'
  end

  def server
    self.class.config[:host]
  end
end
