#!/usr/bin/env ruby
# Make drb server
require 'rubygems'
#require File.expand_path('../lib/in_memory_q_counter', File.dirname(__FILE__))
# This is a non thread safe replacement for the
# couchbase counter mechanism since every test needs
# a clean start and Hash#clear is soooo much faster than
# a couchbase bucket flush
class InMemoryQCounter
  attr_reader :store, :environment

  def initialize(reload_stats: false, environment: nil)
    @store = {}
    @environment = environment || 'development'
    reload_stats! if reload_stats
  end

  def get(key, options = {})
    store[key]
  end

  def set(key, value)
    store[key] = value
  end

  def incr(key, options = {})
    # store[key] ||= options[:initial].to_i
    # store[key] += 1
    if store[key]
      store[key] += 1
    else
      store[key] = options[:initial].to_i
    end
  end

  def decr(key, options = {})
    # store[key] ||= options[:initial].to_i
    # store[key] -= 1
    if store[key]
      store[key] -= 1
    else
      store[key] = options[:initial].to_i
    end
  end

  def flush
    store.clear
  end

  def reload_stats!
    require 'yaml'
    require 'couchrest'
    couch_settings_path = File.join(ENV['MOZO_PATH'], 'config/couchdb.yml')
    puts "Couch settings path: #{couch_settings_path}"
    puts "Environment: #{environment.inspect}"
    couch_settings = YAML.load_file(couch_settings_path)[environment]
    database = couch_settings['database']
    db = CouchRest.database(database)
    view_result = db.view("_design/order/_view/by_supplier_id_and_state", reduce: true, group_level: 2)
    counts = view_result ? view_result['rows'] : nil
    if counts
      counts.each do |count_spec|
        supplier_id, order_state = count_spec['key']
        order_count = count_spec['value']
        case order_state
        when "placed" then set("supplier_counter:#{supplier_id}:orders_placed", order_count)
        when "active" then set("supplier_counter:#{supplier_id}:orders_in_process", order_count)
        end
      end
    end
  rescue RestClient::ResourceNotFound
    # view not available, initialize as zero
  rescue => e
    raise e
  end
end
require 'drb'
require 'daemons'
drb_port = 9022
Daemons.run_proc('DRBcounter', dir_mode: :normal, dir: File.expand_path("#{File.dirname(__FILE__)}/../tmp/pids")) do
  environment = (%w[production staging development test] & ARGV).first
  DRb.start_service "druby://:#{drb_port}", InMemoryQCounter.new(reload_stats: true, environment: environment)
  DRb.thread.join
end
