require 'resque-retry'
require 'resque/plugins/workers/lock'

class BackendMetricJob
  extend ThreeScale::Analytics::ResquePlugin # to flush any analytics calls

  extend Resque::Plugins::Workers::Lock

  @retry_limit = 3
  @retry_delay = 5.minutes
  @queue = :backend_sync

  def self.lock_workers(service_id, metric_id, *)
    "service:#{service_id}/metric:#{metric_id}"
  end

  def self.sync(backend_id, metric_id, metric_system_name)
    Resque.enqueue(self, backend_id, metric_id, metric_system_name)
  end

  def self.perform(backend_id, metric_id, *)
    if (metric = Metric.find_by_id(metric_id))

      ThreeScale::Core::Metric.save(service_id: backend_id,
                                    id: metric_id,
                                    name: metric.system_name,
                                    parent_id: metric.parent_id)
    else
      ThreeScale::Core::Metric.delete(backend_id, metric_id)
    end
  end
end
