module Connectors
  class Server < Base
    include Helpers::DeleteCommand,
      Helpers::ListCommand


    def initialize(db)
      super(db)
    end

    def collection_name
      'servers'
    end

    def servers_find(query, fields=nil)
      query_options = fields.nil? ? {} : {fields: fields}
      list(query, query_options)
    end

    def servers(p=nil, env=nil, names=nil, reserved=nil, fields=:all)
      q = {}
      q['project'] = p unless p.nil? or p.empty?
      q['deploy_env'] = env unless env.nil? or env.empty?
      q['chef_node_name'] = {'$in' => names} unless names.nil? or names.class != Array
      q['reserved_by'] = {'$ne' => nil} unless reserved.nil?
      f = nil
      unless fields == :all
        f = fields
        ['_id', 'chef_node_name'].each do |k|
          f.push(k) unless f.include?(k)
        end
      end
      servers_find(q, f)
    end

    def stack_servers(stack_id, reserved=nil, options={})
      q = {'stack' => stack_id}
      q['reserved_by'] = {'$ne' => nil} unless reserved.nil?
      list(q, options)
    end

    def servers_by_names(names)
      query = {}
      query['chef_node_name'] = {'$in' => names} unless names.nil? or names.class != Array
      list(query)
    end

    def servers_by_project_and_deploy_env project, env
      query = {project: project, deploy_env: env}
      list(query)
    end

    def server_by_instance_id(id)
      find_server('_id' => id)
    end

    def server_by_chef_node_name(name)
      find_server('chef_node_name' => name)
    end

    def servers_by_key(key_name)
      collection.find('key' => key_name).to_a.map { |bson| model_from_bson(bson) }
    end

    def server_insert(server)
      server.created_at = Time.now
      collection.insert(server.to_mongo_hash)
    end

    def server_update(server)
      collection.update({'_id' => server.id}, server.to_hash_without_id)
    end

    def server_set_chef_node_name(server)
      collection.update({'_id' => server.id}, {'$set' => {'chef_node_name' => server.chef_node_name}})
    end

    def stack_servers_delete(stack_id)
      collection.remove('stack' => stack_id)
    end

    def set_server_run_list(id, run_list)
      collection.update({"_id" => id}, {"$set" => {"run_list" => run_list}})
    end

    private

    def model_from_bson(bson)
      Devops::Model::Server.build_from_bson(bson)
    end

    # couldn't be replaced with ShowCommand (_id doesn't neccesary appear in params)
    def find_server(params)
      bson = collection.find(params).to_a.first
      if bson.nil?
        if params.has_key? "_id"
          raise RecordNotFound.new("No server by instance id '#{params["_id"]}' found")
        elsif params.has_key? "chef_node_name"
          raise RecordNotFound.new("No server by node name '#{params["chef_node_name"]}' found")
        else
          raise RecordNotFound.new('Invalid params')
        end
      end
      model_from_bson(bson)
    end
  end

end
