require "mongo"
require "forwardable"

require "db/mongo/connectors/base"

helpers_files = File.join(Devops::Application.root, "db/mongo/connectors/helpers/*.rb")
Dir[helpers_files].each {|file| require file }

connectors_files = File.join(Devops::Application.root, "db/mongo/connectors/*.rb")
Dir[connectors_files].each {|file| require file }

include Mongo

class MongoConnector
  extend Forwardable

  delegate(
    [:stack_templates, :stack_template, :stack_template_insert, :stack_template_delete, :stack_template_update] => :stack_templates_connector,
    [:stacks, :stack, :stack_insert, :stack_delete, :stack_update, :set_stack_run_list,
      :stack_by_id, :lock_persisting_stack, :unlock_persisting_stack] => :stacks_connector,
    [:project_templates, :project_template_insert, :project_template_update,
    :project_template_delete] => :projects_templates_connector,
    [:servers_find, :servers, :stack_servers, :servers_by_names, :server_by_instance_id,
    :server_by_chef_node_name, :servers_by_key, :server_insert,
    :server_delete, :server_update, :server_set_chef_node_name, :stack_servers_delete, :set_server_run_list, :servers_by_project_and_deploy_env] => :servers_connector,
    [:user_auth, :user, :users, :users_names, :user_insert, :user_delete,
    :user_update, :create_root_user, :check_user_privileges] => :users_connector,
    [:keys, :key, :key_insert, :key_delete] => :keys_connector,
    [:insert_statistic, :search_statistic] => :statistics_connector,
    [:provider_accounts, :provider_account_insert, :provider_account_delete, :provider_account] => :provider_accounts_connector
  )

  def initialize(db, host, port=27017, user=nil, password=nil)
    @db = MongoClient.new(host, port).db(db)
    @db.authenticate(user, password) unless user.nil? or password.nil?
  end

  private

  def provider_accounts_connector
    @provider_accounts_connector ||= Connectors::ProviderAccount.new(@db)
  end

  def stack_templates_connector
    @stack_templates_connector ||= Connectors::StackTemplate.new(@db)
  end

  def stacks_connector
    @stack_connector ||= Connectors::Stack.new(@db)
  end

  def projects_templates_connector
    @projects_templates_connector ||= Connectors::ProjectTemplates.new(@db)
  end

  def servers_connector
    @servers_connector ||= Connectors::Server.new(@db)
  end

end
